gpu

package
v0.3.2 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: Apache-2.0 Imports: 25 Imported by: ? 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 gpu provides a portable WebGPU-shaped 3D rendering API built on core's KindGPU surface hook (docs/architecture/gpu.md).

Persistent GPU resources (Buffer, Texture, Sampler, RenderTarget, BindGroupLayout, BindGroup, Pipeline) are scoped to a *core.Scope and released automatically on disposal. Per-frame command recording submits directly to the platform render thread with zero UI view-tree commits.

Index

Constants

View Source
const (
	DefaultFramesInFlight = driver.GPUDefaultFramesInFlight
	MinFramesInFlight     = driver.GPUMinFramesInFlight
	MaxFramesInFlight     = driver.GPUMaxFramesInFlight
)

Frames-in-flight bounds for per-frame ring-buffer pipelining.

View Source
const DRMFormatModInvalid = driver.GPUDRMFormatModInvalid

DRMFormatModInvalid is DRM_FORMAT_MOD_INVALID, the ExternalTextureDesc.Modifier of a DMA-BUF whose layout its driver implies.

View Source
const DebugLabelsEnabled = false

DebugLabelsEnabled reports whether GPU debug labels, groups, and markers are recorded in this build (true under nsgodev or nsgotest, false in release builds).

Variables

This section is empty.

Functions

func DownsampleRGBA2x

func DownsampleRGBA2x(src *image.RGBA) *image.RGBA

DownsampleRGBA2x produces the next mipmap level from src using a 2x2 box filter.

func GenerateMipChainRGBA

func GenerateMipChainRGBA(base *image.RGBA, maxLevels uint32) []*image.RGBA

GenerateMipChainRGBA generates up to maxLevels mipmap images starting from base (level 0) using a 2x2 box filter. When maxLevels is 0, the full chain down to 1x1 is returned.

func MaxMipLevels

func MaxMipLevels(width, height uint32) uint32

MaxMipLevels returns the number of mipmap levels in a full chain from width x height down to 1x1.

func MipSize

func MipSize(width, height, mipLevel uint32) (uint32, uint32)

MipSize returns the width and height of mipLevel for a base texture of width x height (clamped to a minimum of 1x1).

func View

func View(cx *core.Scope, props ViewProps) core.Node

View returns a core.Node hosting a native GPU surface configured by props. On targets where cx.Env().SupportsGPU() is false, it renders props.Children inside a plain container without touching native GPU APIs and reports ErrUnsupported via OnError.

Types

type AddressMode

type AddressMode uint8

AddressMode selects texture coordinate wrapping behavior.

type BindGroup

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

BindGroup binds buffers, textures, and samplers for one shader @group(G).

func (*BindGroup) Close

func (g *BindGroup) Close() error

Close releases the bind group immediately.

func (*BindGroup) Epoch

func (g *BindGroup) Epoch() uint32

Epoch returns the device epoch this bind group currently belongs to.

func (*BindGroup) ID

func (g *BindGroup) ID() uint64

ID returns the bind group's numeric handle.

func (*BindGroup) Valid

func (g *BindGroup) Valid() bool

Valid reports whether g is open and bound to a live device at its current epoch.

type BindGroupDesc

type BindGroupDesc struct {
	Label   string
	Layout  *BindGroupLayout
	Entries []BindGroupEntry
}

BindGroupDesc configures Device.CreateBindGroupDesc.

type BindGroupEntry

type BindGroupEntry struct {
	Binding uint32
	Buffer  *Buffer
	Offset  uint64
	Size    uint64 // 0 binds to the end of Buffer
	Texture *Texture
	Sampler *Sampler
}

BindGroupEntry binds a Buffer, Texture, or Sampler to a slot in a BindGroup.

type BindGroupLayout

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

BindGroupLayout describes the resource schema of a BindGroup slot.

func (*BindGroupLayout) Close

func (l *BindGroupLayout) Close() error

Close releases the bind group layout immediately.

func (*BindGroupLayout) Epoch

func (l *BindGroupLayout) Epoch() uint32

Epoch returns the device epoch this layout currently belongs to.

func (*BindGroupLayout) ID

func (l *BindGroupLayout) ID() uint64

ID returns the layout's numeric handle.

func (*BindGroupLayout) Valid

func (l *BindGroupLayout) Valid() bool

Valid reports whether l is open and bound to a live device at its current epoch.

type BindGroupLayoutDesc

type BindGroupLayoutDesc struct {
	Label   string
	Entries []BindGroupLayoutEntry
}

BindGroupLayoutDesc configures Device.CreateBindGroupLayoutDesc.

type BindGroupLayoutEntry

type BindGroupLayoutEntry struct {
	Binding          uint32
	Visibility       ShaderStageFlags
	Type             BindingType
	HasDynamicOffset bool
}

BindGroupLayoutEntry describes one binding slot in a BindGroupLayout.

type BindingType

type BindingType uint8

BindingType classifies an entry in a BindGroupLayout.

const (
	BindingUniform           BindingType = BindingType(driver.GPUBindingUniform)
	BindingStorageRead       BindingType = BindingType(driver.GPUBindingStorageRead)
	BindingStorage           BindingType = BindingType(driver.GPUBindingStorage)
	BindingTexture           BindingType = BindingType(driver.GPUBindingTexture)
	BindingStorageTexture    BindingType = BindingType(driver.GPUBindingStorageTexture)
	BindingSampler           BindingType = BindingType(driver.GPUBindingSampler)
	BindingComparisonSampler BindingType = BindingType(driver.GPUBindingComparisonSampler)

	// Descriptive aliases for compute and storage bind group layout entries.
	BindingTypeStorageBuffer         = BindingStorage
	BindingTypeReadOnlyStorageBuffer = BindingStorageRead
	BindingTypeStorageTexture        = BindingStorageTexture
)

type BlendComponent

type BlendComponent struct {
	SrcFactor BlendFactor
	DstFactor BlendFactor
	Operation BlendOperation
}

BlendComponent describes one channel's blend equation.

type BlendOp

type BlendOp = BlendOperation

BlendOp is an alias for BlendOperation.

type BlendOperation

type BlendOperation uint8

BlendOperation selects how blended terms combine.

type BlendState

type BlendState struct {
	Color BlendComponent
	Alpha BlendComponent
}

BlendState configures color and alpha blending.

func BlendAdditive

func BlendAdditive() *BlendState

BlendAdditive returns additive blending (src * srcAlpha + dst).

func BlendAlpha

func BlendAlpha() *BlendState

BlendAlpha returns standard non-premultiplied alpha blending (srcAlpha / 1-srcAlpha).

func BlendMultiply

func BlendMultiply() *BlendState

BlendMultiply returns multiplicative blending (src * dst).

func BlendOpaque

func BlendOpaque() *BlendState

BlendOpaque returns opaque replacement blending (src * 1 + dst * 0).

func BlendPremultipliedAlpha

func BlendPremultipliedAlpha() *BlendState

BlendPremultipliedAlpha returns premultiplied alpha blending (1 / 1-srcAlpha).

type Buffer

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

Buffer is a retained GPU vertex, index, uniform, or storage buffer.

func (*Buffer) Close

func (b *Buffer) Close() error

Close releases the buffer immediately. Safe to call more than once.

func (*Buffer) Epoch

func (b *Buffer) Epoch() uint32

Epoch returns the device epoch this buffer currently belongs to.

func (*Buffer) ID

func (b *Buffer) ID() uint64

ID returns the buffer's process-unique numeric handle.

func (*Buffer) Size

func (b *Buffer) Size() uint64

Size returns the buffer's byte length.

func (*Buffer) Usage

func (b *Buffer) Usage() BufferUsage

Usage returns the buffer's usage flags.

func (*Buffer) Valid

func (b *Buffer) Valid() bool

Valid reports whether b is open and bound to a live device at its current epoch.

type BufferCopy

type BufferCopy struct {
	Buffer *Buffer
	Layout DataLayout
}

BufferCopy identifies a buffer region for copy commands.

type BufferDesc

type BufferDesc struct {
	Label    string
	Size     uint64
	Usage    BufferUsage
	Data     []byte // optional initial contents; copied before CreateBuffer returns
	Retained bool   // opt in to automatic recreation with latest data after device loss
}

BufferDesc configures Device.CreateBuffer.

type BufferSlice

type BufferSlice struct {
	Buffer *Buffer // underlying retained GPU buffer
	Offset uint64  // absolute byte offset within Buffer (aligned for dynamic offsets / SetVertexBuffer)
	Size   uint64  // requested byte length
	Slot   int     // frame-in-flight slot index in [0, FramesInFlight)
	Data   []byte  // writable CPU slice of length Size backing this sub-allocation
}

BufferSlice describes one aligned sub-allocation within a RingBuffer's active frame-in-flight slot.

type BufferUsage

type BufferUsage uint32

BufferUsage is a bitmask of permitted uses for a Buffer.

const (
	UsageVertex   BufferUsage = BufferUsage(driver.GPUBufferVertex)
	UsageIndex    BufferUsage = BufferUsage(driver.GPUBufferIndex)
	UsageUniform  BufferUsage = BufferUsage(driver.GPUBufferUniform)
	UsageStorage  BufferUsage = BufferUsage(driver.GPUBufferStorage)
	UsageCopySrc  BufferUsage = BufferUsage(driver.GPUBufferCopySrc)
	UsageCopyDst  BufferUsage = BufferUsage(driver.GPUBufferCopyDst)
	UsageIndirect BufferUsage = BufferUsage(driver.GPUBufferIndirect)

	// BufferUsageStorage is an alias for UsageStorage for storage buffers (var<storage, read> and var<storage, read_write>).
	BufferUsageStorage = UsageStorage
	// BufferUsageIndirect is an alias for UsageIndirect for indirect dispatch buffers.
	BufferUsageIndirect = UsageIndirect
)

type ColorAttachment

type ColorAttachment struct {
	Texture       *Texture
	ResolveTarget *Texture
	MipLevel      uint32
	ArrayLayer    uint32
	LoadOp        LoadOp
	StoreOp       StoreOp
	ClearColor    core.Color
}

ColorAttachment configures a color target of a RenderPass. Texture == nil targets the view's current swapchain drawable.

type ColorTargetState

type ColorTargetState struct {
	Format    TextureFormat
	Blend     *BlendState
	WriteMask ColorWriteMask
}

ColorTargetState configures one color output of a Pipeline.

type ColorWriteMask

type ColorWriteMask uint8

ColorWriteMask selects which channels a pipeline writes. Zero defaults to ColorWriteAll; use ColorWriteNone to disable all color writes.

type CommandBuffer

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

CommandBuffer is an immutable batch of recorded copy commands and render passes.

type CompareFunc

type CompareFunc uint8

CompareFunc selects a depth, stencil, or comparison-sampler test.

type ComputePass

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

ComputePass records compute pipeline state, bind groups, and workgroup dispatches for one compute pass.

func (*ComputePass) Dispatch

func (p *ComputePass) Dispatch(x, y, z uint32) error

Dispatch dispatches (x, y, z) compute workgroups. Returns ErrUnsupported when the device does not support compute shaders, or ErrInvalidDescriptor if the pass has ended or dispatch dimensions are invalid.

func (*ComputePass) DispatchIndirect

func (p *ComputePass) DispatchIndirect(buf *Buffer, offset uint64) error

DispatchIndirect dispatches workgroups whose (x, y, z) uint32 counts are read from buf at byte offset (12 bytes, 4-byte aligned). buf must have UsageIndirect.

func (*ComputePass) End

func (p *ComputePass) End()

End finishes the compute pass and appends it to its owning Encoder.

func (*ComputePass) SetBindGroup

func (p *ComputePass) SetBindGroup(slot uint32, group *BindGroup, dynamicOffsets ...uint32)

SetBindGroup binds group to @group(slot) with optional dynamic offsets.

func (*ComputePass) SetPipeline

func (p *ComputePass) SetPipeline(pipe *ComputePipeline)

SetPipeline binds the active compute pipeline. Closed pipelines and stale handles from a lost device are ignored.

type ComputePipeline

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

ComputePipeline is an immutable GPU compute shader pipeline.

func (*ComputePipeline) Close

func (p *ComputePipeline) Close() error

Close releases the compute pipeline immediately. Safe to call more than once.

func (*ComputePipeline) ID

func (p *ComputePipeline) ID() uint64

ID returns the compute pipeline's numeric handle.

func (*ComputePipeline) Valid

func (p *ComputePipeline) Valid() bool

Valid reports whether p is open and bound to a live device at its current epoch. Compute pipelines are not restored after device loss; recreate them when Valid returns false.

type ComputePipelineDesc

type ComputePipelineDesc struct {
	Label   string
	Compute ShaderStage
	Layouts []*BindGroupLayout
}

ComputePipelineDesc configures Device.CreateComputePipeline.

type CubeFace

type CubeFace = uint32

CubeFace identifies one face (ArrayLayer 0..5) of a DimCube Texture in canonical WebGPU / Metal / Direct3D / OpenGL order.

const (
	CubeFacePosX CubeFace = driver.GPUCubeFacePosX
	CubeFaceNegX CubeFace = driver.GPUCubeFaceNegX
	CubeFacePosY CubeFace = driver.GPUCubeFacePosY
	CubeFaceNegY CubeFace = driver.GPUCubeFaceNegY
	CubeFacePosZ CubeFace = driver.GPUCubeFacePosZ
	CubeFaceNegZ CubeFace = driver.GPUCubeFaceNegZ
)

type CullMode

type CullMode uint8

CullMode selects which faces are culled.

type DMABufPlane

type DMABufPlane struct {
	FD     int
	Offset uint32
	Pitch  uint32
}

DMABufPlane is one plane of a DMA-BUF: its file descriptor, byte offset and row pitch.

type DataLayout

type DataLayout struct {
	Offset       uint64
	BytesPerRow  uint32
	RowsPerImage uint32
}

DataLayout describes linear pixel data layout in a Go byte slice or Buffer.

type DebugEvent

type DebugEvent struct {
	Kind  string
	Label string
	Depth int
}

DebugEvent records a GPU debug label, group, or marker captured by SoftwareRenderer in nsgodev or nsgotest builds.

type DepthStencilAttachment

type DepthStencilAttachment struct {
	Texture        *Texture
	DepthLoadOp    LoadOp
	DepthStoreOp   StoreOp
	ClearDepth     float32
	StencilLoadOp  LoadOp
	StencilStoreOp StoreOp
	ClearStencil   uint32
}

DepthStencilAttachment configures the depth/stencil target of a RenderPass. Texture == nil targets the view's automatic swapchain depth buffer.

type DepthStencilState

type DepthStencilState struct {
	Format              TextureFormat
	DepthWrite          bool
	DepthCompare        CompareFunc
	StencilFront        StencilFaceState
	StencilBack         StencilFaceState
	StencilReadMask     uint32 // 0 defaults to 0xFF
	StencilWriteMask    uint32 // 0 defaults to 0xFF; use StencilKeep ops to disable writes
	DepthBias           int32
	DepthBiasSlopeScale float32
	DepthBiasClamp      float32
}

DepthStencilState configures depth testing, stencil testing, writing, and depth bias.

type Device

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

Device owns persistent GPU resources and submits recorded command buffers for one mounted gpu.View (or a standalone SoftwareRenderer). All methods are called on the engine goroutine.

func (*Device) BeginEncoder

func (d *Device) BeginEncoder() *Encoder

BeginEncoder starts recording a new CommandBuffer.

func (*Device) BeginFrame

func (d *Device) BeginFrame(at time.Time) *Frame

BeginFrame acquires the next ring-buffer slot (frame % FramesInFlight), waits on that slot's previous FrameFence so the CPU never overwrites memory still being read by the GPU, resets all live RingBuffers for that slot, and returns a Frame ready for recording.

func (*Device) CacheStats

func (d *Device) CacheStats() PipelineCacheStats

CacheStats returns the hit/miss/compilation counters of the attached PipelineCache, or a zero PipelineCacheStats if no cache is attached.

func (*Device) Capabilities

func (d *Device) Capabilities() DeviceCapabilities

Capabilities returns the device's limits, optional features, GPU timestamp query support, and supported compressed texture formats.

func (*Device) CompressedFormats

func (d *Device) CompressedFormats() []TextureFormat

CompressedFormats returns the compressed texture formats supported by d.

func (*Device) CreateBindGroup

func (d *Device) CreateBindGroup(cx *core.Scope, layout *BindGroupLayout, entries []BindGroupEntry) (*BindGroup, error)

CreateBindGroup binds resources matching layout, scoped to cx.

func (*Device) CreateBindGroupDesc

func (d *Device) CreateBindGroupDesc(cx *core.Scope, desc BindGroupDesc) (*BindGroup, error)

CreateBindGroupDesc binds resources matching desc.Layout, with an optional debug label stripped in release builds, scoped to cx.

func (*Device) CreateBindGroupLayout

func (d *Device) CreateBindGroupLayout(cx *core.Scope, entries []BindGroupLayoutEntry) (*BindGroupLayout, error)

CreateBindGroupLayout defines the binding schema for one @group(G) slot.

func (*Device) CreateBindGroupLayoutDesc

func (d *Device) CreateBindGroupLayoutDesc(cx *core.Scope, desc BindGroupLayoutDesc) (*BindGroupLayout, error)

CreateBindGroupLayoutDesc defines a labeled binding schema for one @group(G) slot.

func (*Device) CreateBuffer

func (d *Device) CreateBuffer(cx *core.Scope, desc BufferDesc) (*Buffer, error)

CreateBuffer allocates a retained GPU buffer scoped to cx.

func (*Device) CreateComputePipeline

func (d *Device) CreateComputePipeline(cx *core.Scope, desc ComputePipelineDesc) (*ComputePipeline, error)

CreateComputePipeline compiles and validates an immutable compute pipeline scoped to cx. Returns ErrUnsupported on devices where SupportsCompute() is false (such as WebGL 2 and OpenGL ES 3.0).

func (*Device) CreatePipeline

func (d *Device) CreatePipeline(cx *core.Scope, desc PipelineDesc) (*Pipeline, error)

CreatePipeline compiles and validates an immutable render pipeline scoped to cx. When a PipelineCache is attached to d, compiled target shader artifacts are reused across launches without recompilation.

func (*Device) CreatePipelineAsync

func (d *Device) CreatePipelineAsync(cx *core.Scope, desc PipelineDesc, onReady func(*Pipeline, error)) *Pipeline

CreatePipelineAsync validates desc synchronously and compiles target shader artifacts asynchronously off the engine goroutine without blocking frames. The returned *Pipeline starts with Ready() == false and flips to Ready() == true once compilation finishes and the pipeline is submitted to the backend; onReady then runs on the engine goroutine (or synchronously on a standalone renderer).

func (*Device) CreateRenderTarget

func (d *Device) CreateRenderTarget(cx *core.Scope, desc RenderTargetDesc) (*RenderTarget, error)

CreateRenderTarget allocates an offscreen render target (color-only, color+depth, depth-only shadow map, or depth/stencil) whose attachments can be rendered to and sampled by subsequent passes, scoped to cx. With SampleCount 4 the color texture is multisampled and a single-sampled Resolve texture is created for sampling; pass Resolve as the color attachment's ResolveTarget (or call Encoder.ResolveTexture) to fill it.

func (*Device) CreateRingBuffer

func (d *Device) CreateRingBuffer(cx *core.Scope, desc RingBufferDesc) (*RingBuffer, error)

CreateRingBuffer allocates a per-frame streaming RingBuffer partitioned across d.FramesInFlight() slots, scoped to cx.

func (*Device) CreateSampler

func (d *Device) CreateSampler(cx *core.Scope, desc SamplerDesc) (*Sampler, error)

CreateSampler allocates a retained GPU sampler scoped to cx.

func (*Device) CreateTexture

func (d *Device) CreateTexture(cx *core.Scope, desc TextureDesc) (*Texture, error)

CreateTexture allocates a retained GPU texture scoped to cx.

func (*Device) CreateTextureFromImage

func (d *Device) CreateTextureFromImage(cx *core.Scope, src core.ImageSource, desc TextureDesc) (*Texture, error)

CreateTextureFromImage allocates a 2D texture from an ImageSource with Pixels and uploads its RGBA pixels.

func (*Device) CreateTimestampQuery

func (d *Device) CreateTimestampQuery(cx *core.Scope, label string) (*TimestampQuery, error)

CreateTimestampQuery allocates a GPU timestamp query scoped to cx. Returns ErrUnsupported when Device.Capabilities().TimestampQueries is false.

func (*Device) EndFrame

func (d *Device) EndFrame(f *Frame)

EndFrame finalizes f. If f has not yet been submitted and has recorded passes, copies, pending ops, or ring-buffer writes, EndFrame submits it; otherwise it completes f's frame slot and advances to the next slot cleanly. Safe to call more than once or after Frame.Submit.

func (*Device) Epoch

func (d *Device) Epoch() uint32

Epoch returns the device epoch counter (alias of Generation, incremented on every device loss and surface recreation).

func (*Device) Features

func (d *Device) Features() Features

Features returns optional features supported by the device.

func (*Device) FrameIndex

func (d *Device) FrameIndex() uint64

FrameIndex returns the monotonic frame index of the active frame, or the next frame to be started by BeginFrame.

func (*Device) FrameSlot

func (d *Device) FrameSlot() int

FrameSlot returns the ring-buffer slot index [0, FramesInFlight) for the active frame, or the next frame to be started by BeginFrame.

func (*Device) FramesInFlight

func (d *Device) FramesInFlight() int

FramesInFlight returns the configured ring-buffer frame-in-flight count (2 or 3).

func (*Device) GenerateMipmaps

func (d *Device) GenerateMipmaps(tex *Texture) error

GenerateMipmaps populates mip levels 1..MipLevels-1 from level 0 for every array layer (or cubemap face) of tex using a 2x2 box filter. It returns ErrUnsupported where Features.MipmapGeneration is false (the native backends today); there, build the chain on the CPU with GenerateMipChainRGBA and upload each level with WriteTextureMip.

func (*Device) Generation

func (d *Device) Generation() uint32

Generation returns the device generation counter (incremented after device loss).

func (*Device) ImportTexture

func (d *Device) ImportTexture(cx *core.Scope, desc ExternalTextureDesc) (*Texture, error)

ImportTexture opens GPU memory another device or API owns, such as a hardware decoder's frame, as a sampled 2D texture scoped to cx, without copying it. The texture goes into bind groups and is sampled like any other; it cannot be written, copied, read back, rendered to or retained across device loss, so render it to a texture of your own to do those. Close releases what the backend opened, after the frames already submitted finish with it: give the frame back to its owner, such as FFmpeg's pool, once the FrameFence of the last frame that sampled it completes.

The backend opens the memory when the next frame is submitted; an import it rejects, such as a handle that does not open or a format that does not match, arrives on ViewProps.OnError.

func (*Device) IsLost

func (d *Device) IsLost() bool

IsLost reports whether this Device has been invalidated by device/context loss or view disposal.

func (*Device) IsSuspended

func (d *Device) IsSuspended() bool

IsSuspended reports whether GPU frame submission is currently paused because the owning app or surface is in the background.

func (*Device) LastPassTimings

func (d *Device) LastPassTimings() []PassTiming

LastPassTimings returns the most recently completed GPU frame's pass timings.

func (*Device) Limits

func (d *Device) Limits() Limits

Limits returns the device's capability limits.

func (*Device) PipelineCache

func (d *Device) PipelineCache() *PipelineCache

PipelineCache returns the PipelineCache attached to d, or nil.

func (*Device) PrecompilePipelines

func (d *Device) PrecompilePipelines(cx *core.Scope, descs []PipelineDesc, onDone func([]*Pipeline, error)) []*Pipeline

PrecompilePipelines compiles a batch of pipelines asynchronously ahead of first draw without blocking the engine goroutine. It returns the handles in descriptor order immediately; onDone fires once all pipelines have finished compiling (with the first error encountered, if any).

func (*Device) ReadBuffer

func (d *Device) ReadBuffer(buf *Buffer, offset, size uint64, fn func(data []byte, err error))

ReadBuffer asynchronously copies size bytes from buf starting at offset back to CPU memory and invokes fn on the engine goroutine. If size is 0, it reads from offset to the end of buf. buf must have UsageCopySrc. Buffer readback is part of the compute feature set: it returns ErrUnsupported when SupportsCompute() is false.

func (*Device) ReadSurface

func (d *Device) ReadSurface(fn func(rgba []byte, err error))

ReadSurface asynchronously copies the view's current swapchain color buffer back to CPU RGBA bytes and invokes fn on the engine goroutine.

func (*Device) ReadTexture

func (d *Device) ReadTexture(tex *Texture, region TextureRegion, fn func(rgba []byte, err error))

ReadTexture asynchronously copies region of tex back to CPU RGBA bytes and invokes fn on the engine goroutine.

func (*Device) SetPipelineCache

func (d *Device) SetPipelineCache(cache *PipelineCache)

SetPipelineCache attaches a PipelineCache to d so CreatePipeline, CreatePipelineAsync, and PrecompilePipelines reuse compiled artifacts across launches and device restores.

func (*Device) SlotFence

func (d *Device) SlotFence(slot int) *FrameFence

SlotFence returns the most recent FrameFence submitted for ring slot, or nil if slot has not yet been submitted.

func (*Device) Submit

func (d *Device) Submit(cmds ...*CommandBuffer)

Submit hands pending resource ops, flushed ring-buffer slices, and cmds directly to the platform backend off-commit (zero UI view-tree commits per frame). Submissions are suppressed while the device is lost or suspended (app in background).

func (*Device) SupportsCompressedFormat

func (d *Device) SupportsCompressedFormat(format TextureFormat) bool

SupportsCompressedFormat reports whether d supports uploading and sampling compressed textures in format.

func (*Device) SupportsCompute

func (d *Device) SupportsCompute() bool

SupportsCompute reports whether the active device supports @compute shader dispatch and read/write storage buffers. Targets without compute support (such as WebGL 2 and OpenGL ES 3.0) return false.

func (*Device) SupportsExternalTexture

func (d *Device) SupportsExternalTexture(kind ExternalTextureKind) bool

SupportsExternalTexture reports whether d can import textures of kind. Where it is false, ImportTexture returns ErrUnsupported: copy the frame to memory and upload it with WriteTexture instead.

func (*Device) SupportsFormat

func (d *Device) SupportsFormat(format TextureFormat) bool

SupportsFormat reports whether d can create textures in format. Compressed formats follow SupportsCompressedFormat, the import-only FormatR16Unorm and FormatRG16Unorm are never created, and the extended formats (FormatBGRA8UnormSRGB, FormatRG11B10Float, FormatR32Float, FormatRGBA32Float, FormatStencil8) require Features.ExtendedFormats.

func (*Device) SupportsTimestampQueries

func (d *Device) SupportsTimestampQueries() bool

SupportsTimestampQueries reports whether d supports per-pass GPU timing queries.

func (*Device) SurfaceFormat

func (d *Device) SurfaceFormat() TextureFormat

SurfaceFormat returns the swapchain's preferred color texture format.

func (*Device) SurfaceSize

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

SurfaceSize returns the current drawable size in physical pixels.

func (*Device) WaitForFrame

func (d *Device) WaitForFrame(slot int)

WaitForFrame blocks until the GPU completes any in-flight frame using slot.

func (*Device) WaitIdle

func (d *Device) WaitIdle()

WaitIdle blocks until all in-flight frame slots on d have completed.

func (*Device) WriteBuffer

func (d *Device) WriteBuffer(buf *Buffer, offset uint64, data []byte)

WriteBuffer copies data into buf starting at byte offset. Data is cloned before returning so callers may immediately reuse the slice.

func (*Device) WriteCubeFaceRGBA

func (d *Device) WriteCubeFaceRGBA(tex *Texture, face CubeFace, mipLevel uint32, img *image.RGBA)

WriteCubeFaceRGBA uploads img's RGBA pixels into one face (CubeFacePosX..CubeFaceNegZ) of a cubemap texture at mipLevel.

func (*Device) WriteTexture

func (d *Device) WriteTexture(tex *Texture, dst TextureCopy, data []byte, layout DataLayout)

WriteTexture copies raw texel bytes into dst according to layout. The written width is BytesPerRow / bytes-per-texel (clamped to the mip edge), and the row count follows the data length and RowsPerImage, on every backend.

func (*Device) WriteTextureMip

func (d *Device) WriteTextureMip(tex *Texture, mipLevel, arrayLayer uint32, data []byte, bytesPerRow uint32)

WriteTextureMip uploads packed texel bytes for an entire mip level and array layer (or cubemap face 0..5). If bytesPerRow is 0, rows are assumed tightly packed.

func (*Device) WriteTextureRGBA

func (d *Device) WriteTextureRGBA(tex *Texture, mipLevel, arrayLayer uint32, img *image.RGBA)

WriteTextureRGBA uploads img's RGBA pixels into tex at mipLevel and arrayLayer.

func (*Device) WriteTextureRegion

func (d *Device) WriteTextureRegion(dst TextureWrite, data []byte, layout DataLayout)

WriteTextureRegion copies raw texel bytes into a specific mip level, array layer (or cubemap face), and optional sub-rectangle of dst.Texture. Width and Height default to the rest of the mip level from the origin. The source rows (layout.BytesPerRow apart, starting at layout.Offset) are repacked into tight rows of the sub-rectangle width, so only the sub-rectangle is written on every backend. Compressed formats are forwarded to WriteTexture unchanged.

type DeviceCapabilities

type DeviceCapabilities struct {
	Limits            Limits
	Features          Features
	TimestampQueries  bool
	CompressedFormats []TextureFormat
}

DeviceCapabilities summarizes the active GPU device's limits, optional features, timing query support, and supported compressed texture formats. Targets without native compute support (WebGL 2, OpenGL ES 3.0) report Features.Compute false; check Device.SupportsCompute and use a CPU or render-pass fallback there.

type DeviceLostEvent

type DeviceLostEvent struct {
	Reason  DeviceLostReason
	Message string
}

DeviceLostEvent is delivered to ViewProps.OnDeviceLost.

type DeviceLostReason

type DeviceLostReason uint8

DeviceLostReason explains why a GPU device or context was lost.

func (DeviceLostReason) String

func (r DeviceLostReason) String() string

String returns a human-readable name for r.

type Encoder

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

Encoder records render passes and copy commands for one Device.Submit call.

func (*Encoder) BeginComputePass

func (e *Encoder) BeginComputePass() *ComputePass

BeginComputePass starts a compute pass on e. Call ComputePass.End when done. On a device where SupportsCompute() is false the pass records nothing and Dispatch returns ErrUnsupported, so backends without compute never receive a compute pass.

func (*Encoder) BeginRenderPass

func (e *Encoder) BeginRenderPass(desc RenderPassDesc) *RenderPass

BeginRenderPass starts a render pass on e. Call RenderPass.End when done.

func (*Encoder) CopyBufferToBuffer

func (e *Encoder) CopyBufferToBuffer(src *Buffer, srcOffset uint64, dst *Buffer, dstOffset, size uint64)

CopyBufferToBuffer records a buffer-to-buffer copy.

func (*Encoder) CopyBufferToTexture

func (e *Encoder) CopyBufferToTexture(src BufferCopy, dst TextureCopy, width, height, layers uint32)

CopyBufferToTexture records a buffer-to-texture copy.

func (*Encoder) CopyTextureToTexture

func (e *Encoder) CopyTextureToTexture(src, dst TextureCopy, width, height, layers uint32)

CopyTextureToTexture records a texture-to-texture copy.

func (*Encoder) Finish

func (e *Encoder) Finish() *CommandBuffer

Finish seals the encoder into an immutable CommandBuffer.

func (*Encoder) InsertDebugMarker

func (e *Encoder) InsertDebugMarker(label string)

InsertDebugMarker inserts an instantaneous debug marker into GPU captures. It is a zero-cost no-op in release builds (without nsgodev or nsgotest).

func (*Encoder) PopDebugGroup

func (e *Encoder) PopDebugGroup()

PopDebugGroup ends the most recent Encoder.PushDebugGroup. It is a zero-cost no-op in release builds (without nsgodev or nsgotest).

func (*Encoder) PushDebugGroup

func (e *Encoder) PushDebugGroup(label string)

PushDebugGroup begins a nested debug group in GPU captures (Metal/RenderDoc/WebGPU). It is a zero-cost no-op in release builds (without nsgodev or nsgotest).

func (*Encoder) ResolveTexture

func (e *Encoder) ResolveTexture(src, dst TextureCopy)

ResolveTexture records a resolve of the multisampled src texture into the single-sampled dst texture (mip level 0, layer 0). It is recorded as a render pass that loads src and resolves it into dst at the end, so it runs in order with the encoder's other passes on every backend that supports MSAA resolve targets. Mismatched sizes or formats, or a src that is not multisampled, record nothing.

type Error

type Error struct {
	Code    ErrorCode
	Message string
	Cause   error
}

Error is a structured GPU validation or asynchronous backend error.

func (Error) Error

func (e Error) Error() string

func (Error) Is

func (e Error) Is(target error) bool

func (Error) Unwrap

func (e Error) Unwrap() error

type ErrorCode

type ErrorCode uint8

ErrorCode classifies a GPU validation or runtime failure.

func (ErrorCode) Error

func (c ErrorCode) Error() string

type ExternalTextureDesc

type ExternalTextureDesc struct {
	Label string
	Kind  ExternalTextureKind
	// Width and Height are the plane's size in texels.
	Width, Height uint32
	// Format is the plane's format as the shader samples it: FormatR8Unorm, FormatRG8Unorm, FormatR16Unorm, FormatRG16Unorm, FormatRGBA8Unorm or FormatBGRA8Unorm.
	Format TextureFormat

	// Handle is the shared texture's NT handle (ExternalD3D11Shared).
	Handle uintptr
	// Plane picks the plane of an NV12 or P010 texture: 0 for luma, 1 for chroma (ExternalD3D11Shared).
	Plane uint32
	// KeyedMutex makes the backend hold the texture's IDXGIKeyedMutex while a submitted frame reads it, acquiring AcquireKey and releasing ReleaseKey (ExternalD3D11Shared). The texture must have been created with D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX; with both keys 0 it is a plain mutex. Each submitted frame that binds the texture takes AcquireKey and releases ReleaseKey again, so use keys that allow repeated reads (such as equal keys) or sample each import in one frame only.
	KeyedMutex bool
	AcquireKey uint64
	ReleaseKey uint64

	// FourCC is the plane's single-plane DRM format: DRM_FORMAT_R8, GR88, R16, GR1616, ABGR8888, XBGR8888, ARGB8888 or XRGB8888 (ExternalDMABuf).
	FourCC uint32
	// Modifier is the DRM format modifier: 0 for DRM_FORMAT_MOD_LINEAR, DRMFormatModInvalid for none (ExternalDMABuf).
	Modifier uint64
	// Planes holds the plane's DMA-BUF, one (ExternalDMABuf).
	Planes []DMABufPlane
}

ExternalTextureDesc describes a texture Device.ImportTexture opens from GPU memory another device or API owns.

An import is one plane sampled as a plain 2D texture: import a planar NV12 frame as two textures, its luma as FormatR8Unorm and its chroma as FormatRG8Unorm at half the size, and convert to RGB in the shader. A 10-bit P010 frame's planes are FormatR16Unorm and FormatRG16Unorm.

The caller keeps ownership of Handle and the planes' FDs: keep them open until the FrameFence of the first frame submitted after ImportTexture completes, after which the backend holds its own reference, and close them yourself.

type ExternalTextureKind

type ExternalTextureKind uint8

ExternalTextureKind identifies the GPU memory Device.ImportTexture opens.

const (
	// ExternalD3D11Shared is a Direct3D 11 texture another device shares through an NT handle (IDXGIResource1::CreateSharedHandle), such as a D3D11VA decoder's frame. Windows only.
	ExternalD3D11Shared ExternalTextureKind = ExternalTextureKind(driver.GPUExternalD3D11Shared)
	// ExternalDMABuf is a Linux DMA-BUF, such as a VAAPI surface exported with vaExportSurfaceHandle or a GBM buffer. Linux only, where GTK's GL context runs on EGL.
	ExternalDMABuf ExternalTextureKind = ExternalTextureKind(driver.GPUExternalDMABuf)
)

type Features

type Features struct {
	StorageBuffers         bool
	StorageTextures        bool
	Compute                bool
	MSAA4x                 bool
	Depth32Float           bool
	Anisotropy             bool
	TimestampQueries       bool
	TextureCompressionBC   bool
	TextureCompressionETC2 bool
	TextureCompressionASTC bool
	// ExtendedFormats reports support for FormatBGRA8UnormSRGB, FormatRG11B10Float, FormatR32Float, FormatRGBA32Float and FormatStencil8 textures and render targets.
	ExtendedFormats bool
	// StencilTest reports support for pipeline stencil testing (DepthStencilState.StencilFront/StencilBack and the stencil read/write masks).
	StencilTest bool
	// MipmapGeneration reports support for Device.GenerateMipmaps. Where it is false, build the chain on the CPU (GenerateMipChainRGBA) and upload each level with WriteTextureMip.
	MipmapGeneration bool
	// ImportD3D11Shared and ImportDMABuf report support for Device.ImportTexture of ExternalD3D11Shared and ExternalDMABuf textures (Device.SupportsExternalTexture).
	ImportD3D11Shared bool
	ImportDMABuf      bool
}

Features reports optional capabilities supported by the active GPU device.

type FilterMode

type FilterMode uint8

FilterMode selects texture minification, magnification, or mipmap filtering.

type Frame

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

Frame is the per-frame recording context handed to ViewProps.OnFrame or returned by Device.BeginFrame.

func (*Frame) BeginComputePass

func (f *Frame) BeginComputePass() *ComputePass

BeginComputePass starts a ComputePass recorded into this frame.

func (*Frame) BeginRenderPass

func (f *Frame) BeginRenderPass(desc RenderPassDesc) *RenderPass

BeginRenderPass starts a RenderPass recorded into this frame.

func (*Frame) CopyBufferToBuffer

func (f *Frame) CopyBufferToBuffer(src *Buffer, srcOffset uint64, dst *Buffer, dstOffset, size uint64)

CopyBufferToBuffer records a buffer copy into this frame.

func (*Frame) CopyBufferToTexture

func (f *Frame) CopyBufferToTexture(src BufferCopy, dst TextureCopy, width, height, layers uint32)

CopyBufferToTexture records a buffer-to-texture copy into this frame.

func (*Frame) CopyTextureToTexture

func (f *Frame) CopyTextureToTexture(src, dst TextureCopy, width, height, layers uint32)

CopyTextureToTexture records a texture-to-texture copy into this frame.

func (*Frame) Delta

func (f *Frame) Delta() time.Duration

Delta returns the elapsed time since the previous frame.

func (*Frame) Device

func (f *Frame) Device() *Device

Device returns the owning GPU Device.

func (*Frame) End

func (f *Frame) End()

End finalizes this frame via Device.EndFrame.

func (*Frame) Fence

func (f *Frame) Fence() *FrameFence

Fence returns the FrameFence signaled when the GPU finishes executing f.

func (*Frame) FrameIndex

func (f *Frame) FrameIndex() uint64

FrameIndex returns this frame's monotonic frame index.

func (*Frame) FrameSlot

func (f *Frame) FrameSlot() int

FrameSlot returns this frame's ring-buffer slot index [0, FramesInFlight).

func (*Frame) InsertDebugMarker

func (f *Frame) InsertDebugMarker(label string)

InsertDebugMarker inserts an instantaneous debug marker on this frame's encoder. It is a zero-cost no-op in release builds (without nsgodev or nsgotest).

func (*Frame) PassTimings

func (f *Frame) PassTimings() []PassTiming

PassTimings returns the most recently completed GPU frame's per-pass timings (or the current frame's timings after Submit on synchronous software devices).

func (*Frame) PopDebugGroup

func (f *Frame) PopDebugGroup()

PopDebugGroup closes the most recent Frame.PushDebugGroup. It is a zero-cost no-op in release builds (without nsgodev or nsgotest).

func (*Frame) PushDebugGroup

func (f *Frame) PushDebugGroup(label string)

PushDebugGroup begins a nested debug group on this frame's encoder. It is a zero-cost no-op in release builds (without nsgodev or nsgotest).

func (*Frame) ResolveTexture

func (f *Frame) ResolveTexture(src, dst TextureCopy)

ResolveTexture explicitly resolves a multisampled texture into a single-sampled texture.

func (*Frame) Size

func (f *Frame) Size() (width, height int)

Size returns the current swapchain dimensions in physical pixels.

func (*Frame) Submit

func (f *Frame) Submit()

Submit submits this frame's recorded commands off-commit and ends the frame. Safe to call once; ViewProps.OnFrame automatically finishes the frame if the callback does not call Submit or End.

func (*Frame) Time

func (f *Frame) Time() time.Time

Time returns the frame's display timestamp.

type FrameFence

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

FrameFence tracks GPU completion of one submitted frame and its ring-buffer slot. Waiting on the previous FrameFence for slot (frame % FramesInFlight) before writing that slot guarantees the CPU never overwrites memory the GPU is still reading.

func (*FrameFence) FrameIndex

func (f *FrameFence) FrameIndex() uint64

FrameIndex returns the monotonic frame index associated with this fence.

func (*FrameFence) FrameSlot

func (f *FrameFence) FrameSlot() int

FrameSlot returns the ring-buffer slot index [0, FramesInFlight) guarded by f.

func (*FrameFence) ID

func (f *FrameFence) ID() uint64

ID returns the fence's monotonic identifier.

func (*FrameFence) Signaled

func (f *FrameFence) Signaled() bool

Signaled reports whether the GPU has finished executing the frame guarded by f.

func (*FrameFence) Wait

func (f *FrameFence) Wait()

Wait blocks until the GPU signals completion of the frame guarded by f.

func (*FrameFence) WaitTimeout

func (f *FrameFence) WaitTimeout(d time.Duration) bool

WaitTimeout waits up to d for the fence to be signaled, reporting whether it became signaled before the timeout elapsed.

type FrontFace

type FrontFace uint8

FrontFace selects the winding order considered front-facing.

const (
	FrontCCW     FrontFace = FrontFace(driver.GPUFrontCCW)
	FrontCW      FrontFace = FrontFace(driver.GPUFrontCW)
	FrontFaceCCW FrontFace = FrontCCW
	FrontFaceCW  FrontFace = FrontCW
)

type IndexFormat

type IndexFormat uint8

IndexFormat specifies the element width of an index buffer.

type Limits

type Limits struct {
	MaxTextureDimension2D         uint32
	MaxBufferSize                 uint64
	MaxUniformBufferSize          uint64
	MaxStorageBufferBindingSize   uint64
	MaxBindGroups                 uint32
	MaxVertexBuffers              uint32
	MaxVertexAttributes           uint32
	MinUniformBufferAlignment     uint32
	MaxComputeWorkgroupSizeX      uint32
	MaxComputeWorkgroupSizeY      uint32
	MaxComputeWorkgroupSizeZ      uint32
	MaxComputeInvocationsPerGroup uint32
	MaxComputeWorkgroupsPerDim    uint32
	MaxColorAttachments           uint32
	MaxTextureArrayLayers         uint32
}

Limits reports the active GPU device's capability limits.

type LoadOp

type LoadOp uint8

LoadOp selects how an attachment is initialized at the start of a RenderPass.

const (
	LoadClear LoadOp = LoadOp(driver.GPULoadClear)
	LoadLoad  LoadOp = LoadOp(driver.GPULoadLoad)
)

type PassTiming

type PassTiming struct {
	Label     string
	PassIndex int
	Duration  time.Duration
}

PassTiming reports the measured GPU execution duration of one render pass.

type Pipeline

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

Pipeline is an immutable vertex+fragment GPU render pipeline.

func (*Pipeline) CacheKey

func (p *Pipeline) CacheKey() string

CacheKey returns the deterministic pipeline cache key computed from the pipeline's shaders and render state.

func (*Pipeline) Close

func (p *Pipeline) Close() error

Close releases the pipeline immediately.

func (*Pipeline) Done

func (p *Pipeline) Done() <-chan struct{}

Done returns a channel that closes when asynchronous pipeline compilation completes (or is already closed for synchronously created pipelines).

func (*Pipeline) Epoch

func (p *Pipeline) Epoch() uint32

Epoch returns the device epoch this pipeline currently belongs to.

func (*Pipeline) Err

func (p *Pipeline) Err() error

Err returns the asynchronous compilation error, if any, once Done is closed.

func (*Pipeline) ID

func (p *Pipeline) ID() uint64

ID returns the pipeline's numeric handle.

func (*Pipeline) Ready

func (p *Pipeline) Ready() bool

Ready reports whether p has finished compiling (for asynchronous precompilation) and is valid for binding in a RenderPass.

func (*Pipeline) Valid

func (p *Pipeline) Valid() bool

Valid reports whether p is open and bound to a live device at its current epoch.

type PipelineCache

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

PipelineCache persists compiled GPU pipeline target artifacts (MSL, HLSL, GLSL 3.30, GLSL ES 3.00, WGSL, and optional backend PSO/binary archive blobs) across launches so subsequent runs reuse cached pipelines without shader recompilation or first-draw hitches.

Metadata and portable shader artifacts are stored as deterministic, versioned JSON files (never encoding/gob). PipelineCache is safe for concurrent use by asynchronous precompilation goroutines.

func NewMemoryPipelineCache

func NewMemoryPipelineCache() *PipelineCache

NewMemoryPipelineCache creates an in-memory PipelineCache with no disk I/O.

func NewPipelineCache

func NewPipelineCache(dir string) (*PipelineCache, error)

NewPipelineCache opens or creates a persistent PipelineCache backed by dir. When dir is empty, the cache operates in memory only. Existing valid cache entries in dir are loaded immediately so a second launch hits the cache with zero shader recompilation.

func (*PipelineCache) CacheStats

func (c *PipelineCache) CacheStats() PipelineCacheStats

CacheStats returns a snapshot of the cache's hit, miss, store, entry, and shader compilation counters.

func (*PipelineCache) Clear

func (c *PipelineCache) Clear() error

Clear removes all cached pipeline entries and backend blobs from memory and from the backing directory (if any).

func (*PipelineCache) Dir

func (c *PipelineCache) Dir() string

Dir returns the cache's backing directory, or "" for an in-memory cache.

func (*PipelineCache) GetBackendBlob

func (c *PipelineCache) GetBackendBlob(key, backend string) ([]byte, bool)

GetBackendBlob retrieves a previously stored backend-native binary cache blob for key and backend name.

func (*PipelineCache) Has

func (c *PipelineCache) Has(key string) bool

Has reports whether an entry with deterministic key exists in the cache.

func (*PipelineCache) PutBackendBlob

func (c *PipelineCache) PutBackendBlob(key, backend string, data []byte) error

PutBackendBlob persists an opaque backend-native compiled pipeline cache blob (for example a Metal binary archive, Vulkan VkPipelineCache, or D3D11/12 PSO library) associated with key and backend name (e.g. "metal", "vulkan", "d3d11").

func (*PipelineCache) ResetStats

func (c *PipelineCache) ResetStats()

ResetStats zeroes hit, miss, store, and compilation counters while keeping all cached entries intact.

type PipelineCacheStats

type PipelineCacheStats struct {
	Hits         uint64
	Misses       uint64
	Stores       uint64
	Entries      int
	Compilations uint64
}

PipelineCacheStats reports cache hit, miss, store, and compilation counts for a PipelineCache.

type PipelineDesc

type PipelineDesc struct {
	Label         string
	Vertex        ShaderStage
	Fragment      ShaderStage
	Layouts       []*BindGroupLayout
	VertexBuffers []VertexBufferLayout
	Primitive     PrimitiveState
	DepthStencil  *DepthStencilState
	Targets       []ColorTargetState
	SampleCount   int
	Retained      bool // opt in to automatic recreation after device loss
}

PipelineDesc configures Device.CreatePipeline and Device.CreatePipelineAsync.

type PrimitiveState

type PrimitiveState struct {
	Topology  PrimitiveTopology
	FrontFace FrontFace
	CullMode  CullMode
}

PrimitiveState configures primitive assembly and culling.

type PrimitiveTopology

type PrimitiveTopology uint8

PrimitiveTopology selects how vertices are assembled into primitives.

type RenderPass

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

RenderPass records drawing state and draw calls for one render pass.

func (*RenderPass) ClearColor

func (p *RenderPass) ClearColor(c core.Color)

ClearColor configures color attachment 0 to clear to c at pass start.

func (*RenderPass) ClearDepth

func (p *RenderPass) ClearDepth(depth float32)

ClearDepth configures the depth attachment to clear to depth at pass start.

func (*RenderPass) ClearStencil

func (p *RenderPass) ClearStencil(stencil uint32)

ClearStencil configures the stencil attachment to clear to stencil at pass start.

func (*RenderPass) Draw

func (p *RenderPass) Draw(vertexCount, firstVertex uint32)

Draw draws vertexCount non-indexed vertices starting at firstVertex.

func (*RenderPass) DrawIndexed

func (p *RenderPass) DrawIndexed(indexCount, firstIndex uint32, baseVertex int32)

DrawIndexed draws indexCount indexed vertices.

func (*RenderPass) DrawIndexedInstanced

func (p *RenderPass) DrawIndexedInstanced(indexCount, instanceCount, firstIndex uint32, baseVertex int32, firstInstance uint32)

DrawIndexedInstanced draws instanceCount instances of indexCount indexed vertices.

func (*RenderPass) DrawInstanced

func (p *RenderPass) DrawInstanced(vertexCount, instanceCount, firstVertex, firstInstance uint32)

DrawInstanced draws instanceCount instances of vertexCount vertices.

func (*RenderPass) End

func (p *RenderPass) End()

End finishes the render pass and appends it to its owning Encoder.

func (*RenderPass) InsertDebugMarker

func (p *RenderPass) InsertDebugMarker(label string)

InsertDebugMarker inserts an instantaneous debug marker inside this render pass. It is a zero-cost no-op in release builds (without nsgodev or nsgotest).

func (*RenderPass) PopDebugGroup

func (p *RenderPass) PopDebugGroup()

PopDebugGroup closes the most recent RenderPass.PushDebugGroup. It is a zero-cost no-op in release builds (without nsgodev or nsgotest).

func (*RenderPass) PushDebugGroup

func (p *RenderPass) PushDebugGroup(label string)

PushDebugGroup begins a nested debug group inside this render pass. It is a zero-cost no-op in release builds (without nsgodev or nsgotest).

func (*RenderPass) SetBindGroup

func (p *RenderPass) SetBindGroup(slot uint32, group *BindGroup, dynamicOffsets ...uint32)

SetBindGroup binds group to @group(slot) with optional dynamic offsets.

func (*RenderPass) SetBlendConstant

func (p *RenderPass) SetBlendConstant(r, g, b, a float32)

SetBlendConstant sets the constant blend color.

func (*RenderPass) SetIndexBuffer

func (p *RenderPass) SetIndexBuffer(buf *Buffer, format IndexFormat, offset uint64)

SetIndexBuffer binds buf as the active index buffer.

func (*RenderPass) SetPipeline

func (p *RenderPass) SetPipeline(pipe *Pipeline)

SetPipeline binds the active render pipeline. Stale handles from a lost device or pipelines still compiling asynchronously are safely ignored, and subsequent draws are skipped until a valid ready pipeline is bound.

func (*RenderPass) SetScissor

func (p *RenderPass) SetScissor(x, y, width, height int32)

SetScissor restricts rendering to the given pixel scissor rectangle.

func (*RenderPass) SetStencilReference

func (p *RenderPass) SetStencilReference(ref uint32)

SetStencilReference sets the stencil reference value.

func (*RenderPass) SetVertexBuffer

func (p *RenderPass) SetVertexBuffer(slot uint32, buf *Buffer, offset uint64)

SetVertexBuffer binds buf to vertex buffer slot starting at byte offset.

func (*RenderPass) SetViewport

func (p *RenderPass) SetViewport(x, y, width, height, minDepth, maxDepth float32)

SetViewport sets the rasterizer viewport rectangle and depth range.

type RenderPassDesc

type RenderPassDesc struct {
	// Label names the render pass in GPU capture tools (stripped in release builds).
	Label string
	// TimingLabel opts this pass into per-pass GPU timing queries when Device.Capabilities().TimestampQueries is true.
	TimingLabel string
	// TimestampQuery optionally binds a TimestampQuery resource to receive this pass's measured GPU execution duration.
	TimestampQuery   *TimestampQuery
	ColorAttachments []ColorAttachment
	DepthStencil     *DepthStencilAttachment
}

RenderPassDesc configures Encoder.BeginRenderPass and Frame.BeginRenderPass.

type RenderTarget

type RenderTarget struct {
	Color   *Texture
	Resolve *Texture // non-nil when created with SampleCount > 1
	Depth   *Texture
	Width   uint32
	Height  uint32
	// contains filtered or unexported fields
}

RenderTarget pairs an offscreen color Texture with optional MSAA Resolve and depth/stencil Textures.

func (*RenderTarget) Close

func (rt *RenderTarget) Close() error

Close releases the render target's color, resolve, and depth/stencil textures.

func (*RenderTarget) Epoch

func (rt *RenderTarget) Epoch() uint32

Epoch returns the device epoch of the render target's attachment.

func (*RenderTarget) Valid

func (rt *RenderTarget) Valid() bool

Valid reports whether rt is open and its underlying textures are valid.

type RenderTargetDesc

type RenderTargetDesc struct {
	Label       string
	Width       uint32
	Height      uint32
	ColorFormat TextureFormat
	DepthFormat TextureFormat
	SampleCount int  // 0 or 1; 4 for a multisampled target with a Resolve texture
	Retained    bool // opt in to automatic recreation after device loss
}

RenderTargetDesc configures Device.CreateRenderTarget.

Set ColorFormat for a color-only offscreen target, both ColorFormat and DepthFormat for a color+depth target, or DepthFormat alone (with ColorFormat == FormatUndefined) for a depth-only target such as a shadow map. When both formats are FormatUndefined, ColorFormat defaults to FormatRGBA8Unorm. All created attachments include TextureRenderAttachment, TextureSampled, and TextureCopySrc so subsequent passes can sample or read them back.

type RingBuffer

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

RingBuffer is a multi-buffered per-frame streaming allocator backed by one persistent GPU Buffer partitioned into Device.FramesInFlight() disjoint slots.

During frame k (slot s = k % N), Alloc and Write sub-allocate aligned slices within slot s while the GPU may still read slot (k-1) % N with zero stalls and zero write-while-read corruption. Device.BeginFrame waits on slot s's previous FrameFence before resetting slot s's write cursor, and Frame.Submit / Device.EndFrame flushes slot s's dirty range in a single bulk upload.

func (*RingBuffer) Alignment

func (r *RingBuffer) Alignment() uint64

Alignment returns the byte alignment applied to every Alloc/Write call.

func (*RingBuffer) Alloc

func (r *RingBuffer) Alloc(size uint64) (BufferSlice, uint32, error)

Alloc reserves size bytes in the active frame slot, aligned to r.Alignment() (256 bytes by default for uniform ring buffers), and returns the BufferSlice together with its uint32 dynamic offset for RenderPass.SetBindGroup.

func (*RingBuffer) Buffer

func (r *RingBuffer) Buffer() *Buffer

Buffer returns the underlying retained GPU Buffer backing all frame slots. Bind it once in a BindGroup with HasDynamicOffset: true (for UsageUniform) or pass it with slice.Offset to RenderPass.SetVertexBuffer / SetIndexBuffer.

func (*RingBuffer) Close

func (r *RingBuffer) Close() error

Close releases the ring buffer and its underlying GPU Buffer. Safe to call more than once.

func (*RingBuffer) CurrentSlot

func (r *RingBuffer) CurrentSlot() int

CurrentSlot returns the active frame-in-flight slot index on the owning Device.

func (*RingBuffer) FramesInFlight

func (r *RingBuffer) FramesInFlight() int

FramesInFlight returns the number of rotating frame slots in r.

func (*RingBuffer) Remaining

func (r *RingBuffer) Remaining() uint64

Remaining returns the unallocated byte capacity remaining in the current frame slot.

func (*RingBuffer) SlotOffset

func (r *RingBuffer) SlotOffset(slot int) uint64

SlotOffset returns the base byte offset of slot within the underlying Buffer.

func (*RingBuffer) SlotSize

func (r *RingBuffer) SlotSize() uint64

SlotSize returns the aligned byte capacity available in each frame slot.

func (*RingBuffer) TotalSize

func (r *RingBuffer) TotalSize() uint64

TotalSize returns the total byte size of the backing GPU buffer across all slots.

func (*RingBuffer) Used

func (r *RingBuffer) Used() uint64

Used returns the aligned byte count allocated so far in the current frame slot.

func (*RingBuffer) Write

func (r *RingBuffer) Write(data []byte) (BufferSlice, uint32, error)

Write allocates len(data) aligned bytes in the active frame slot, copies data into the slot, and returns the BufferSlice and its uint32 dynamic offset.

type RingBufferDesc

type RingBufferDesc struct {
	Label string
	// SlotSize is the byte capacity available per frame-in-flight slot.
	// Total underlying GPU buffer capacity is SlotSize (rounded up to Alignment)
	// multiplied by Device.FramesInFlight().
	SlotSize uint64
	// Usage selects how the ring buffer is bound (e.g. UsageUniform, UsageVertex,
	// UsageIndex, or a combination). UsageCopyDst is always included.
	Usage BufferUsage
	// Alignment overrides the per-allocation byte alignment. When zero, uniform
	// ring buffers align to Device.Limits().MinUniformBufferAlignment (256 bytes)
	// and non-uniform ring buffers align to 16 bytes.
	Alignment uint64
}

RingBufferDesc configures Device.CreateRingBuffer.

type Sampler

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

Sampler is a retained GPU texture sampler.

func (*Sampler) Close

func (s *Sampler) Close() error

Close releases the sampler immediately.

func (*Sampler) Desc

func (s *Sampler) Desc() SamplerDesc

Desc returns the sampler's descriptor.

func (*Sampler) Epoch

func (s *Sampler) Epoch() uint32

Epoch returns the device epoch this sampler currently belongs to.

func (*Sampler) ID

func (s *Sampler) ID() uint64

ID returns the sampler's numeric handle.

func (*Sampler) Valid

func (s *Sampler) Valid() bool

Valid reports whether s is open and bound to a live device at its current epoch.

type SamplerDesc

type SamplerDesc struct {
	Label         string
	MinFilter     FilterMode
	MagFilter     FilterMode
	MipmapFilter  FilterMode
	AddressU      AddressMode
	AddressV      AddressMode
	AddressW      AddressMode
	MinLOD        float32 // honoured by the software device; native backends do not clamp LOD yet
	MaxLOD        float32 // 0 defaults to 32.0 (unbounded); honoured by the software device only for now
	Compare       CompareFunc
	MaxAnisotropy uint16
	Retained      bool // opt in to automatic recreation after device loss
}

SamplerDesc configures Device.CreateSampler.

type ShaderDesc

type ShaderDesc struct {
	Label  string
	Source string
}

ShaderDesc configures CompileShader.

type ShaderModule

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

ShaderModule is a portable compiled WGSL or Kage shader module ready to be attached to one or more Pipelines or ComputePipelines.

func CompileKage

func CompileKage(src string) (*ShaderModule, error)

CompileKage compiles a Kage fragment shader into a ShaderModule.

func CompileShader

func CompileShader(desc ShaderDesc) (*ShaderModule, error)

CompileShader parses, type-checks, and lowers desc.Source (WGSL) into a ShaderModule, recording desc.Label in nsgodev/nsgotest builds only.

func CompileWGSL

func CompileWGSL(src string) (*ShaderModule, error)

CompileWGSL parses, type-checks, and lowers a WGSL 3D or compute pipeline module into portable shaderir.

func MustCompileWGSL

func MustCompileWGSL(src string) *ShaderModule

MustCompileWGSL compiles src and panics if compilation fails.

func (*ShaderModule) HasComputeEntry

func (m *ShaderModule) HasComputeEntry(name string) bool

HasComputeEntry reports whether m defines a @compute entry point named name (or any compute entry point when name is empty).

func (*ShaderModule) HasFragmentEntry

func (m *ShaderModule) HasFragmentEntry(name string) bool

HasFragmentEntry reports whether m defines a @fragment entry point named name (or any fragment entry point when name is empty).

func (*ShaderModule) HasVertexEntry

func (m *ShaderModule) HasVertexEntry(name string) bool

HasVertexEntry reports whether m defines a @vertex entry point named name (or any vertex entry point when name is empty).

func (*ShaderModule) Label

func (m *ShaderModule) Label() string

Label returns the shader module's debug label (always empty in release builds).

func (*ShaderModule) WorkgroupSize

func (m *ShaderModule) WorkgroupSize() [3]uint32

WorkgroupSize returns the @workgroup_size(X, Y, Z) of m's compute entry point, or [0, 0, 0] if m has no compute entry point.

type ShaderStage

type ShaderStage struct {
	Module     *ShaderModule
	EntryPoint string
}

ShaderStage names a compiled ShaderModule and its entry point function.

type ShaderStageFlags

type ShaderStageFlags uint8

ShaderStageFlags specifies which shader stages see a binding.

type SoftwareRenderer

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

SoftwareRenderer hosts a standalone, deterministic pure-Go software 3D GPU device for headless unit tests and offscreen rendering without a UI window.

func NewSoftwareRenderer

func NewSoftwareRenderer(width, height int, depthFormat TextureFormat) *SoftwareRenderer

NewSoftwareRenderer creates a pure-Go software 3D GPU renderer with a swapchain of width x height pixels, an optional depthFormat (e.g. FormatDepth24Plus), and DefaultFramesInFlight (2) ring-buffer slots. Compute shaders, storage buffers, and storage textures are enabled by default.

func NewSoftwareRendererWithConfig

func NewSoftwareRendererWithConfig(width, height int, colorFormat, depthFormat TextureFormat, sampleCount int) *SoftwareRenderer

NewSoftwareRendererWithConfig creates a pure-Go software 3D GPU renderer with an explicit swapchain color format (FormatUndefined means FormatRGBA8Unorm), depth/stencil format, and MSAA sample count (1 or 4).

func NewSoftwareRendererWithFeatures

func NewSoftwareRendererWithFeatures(width, height int, depthFormat TextureFormat, features Features) *SoftwareRenderer

NewSoftwareRendererWithFeatures creates a pure-Go software 3D GPU renderer with explicit device capability flags (useful for testing unsupported feature paths).

func NewSoftwareRendererWithFrames

func NewSoftwareRendererWithFrames(width, height int, depthFormat TextureFormat, framesInFlight int) *SoftwareRenderer

NewSoftwareRendererWithFrames creates a pure-Go software 3D GPU renderer with framesInFlight ring-buffer slots, clamped to [MinFramesInFlight, MaxFramesInFlight].

func (*SoftwareRenderer) Close

func (r *SoftwareRenderer) Close()

Close flushes pending work and stops any pipelined worker goroutine.

func (*SoftwareRenderer) DebugEvents

func (r *SoftwareRenderer) DebugEvents() []DebugEvent

DebugEvents returns all debug labels, groups, and markers observed by the software renderer (empty in release builds where labels are stripped).

func (*SoftwareRenderer) Device

func (r *SoftwareRenderer) Device() *Device

Device returns the gpu.Device backed by this software rasterizer.

func (*SoftwareRenderer) FrameCount

func (r *SoftwareRenderer) FrameCount() int

FrameCount returns how many GPU frames have been submitted.

func (*SoftwareRenderer) Image

func (r *SoftwareRenderer) Image() *image.RGBA

Image returns an independent RGBA snapshot of the rendered swapchain surface.

func (*SoftwareRenderer) LastError

func (r *SoftwareRenderer) LastError() error

LastError returns the last execution error reported by the software device.

func (*SoftwareRenderer) PassTimings

func (r *SoftwareRenderer) PassTimings() []PassTiming

PassTimings returns the per-pass timings measured during the most recent frame.

func (*SoftwareRenderer) Resize

func (r *SoftwareRenderer) Resize(width, height int)

Resize updates the software swapchain size in pixels.

func (*SoftwareRenderer) ResourceLabel

func (r *SoftwareRenderer) ResourceLabel(id uint64) string

ResourceLabel returns the debug label received by the software renderer for resource id (always empty in release builds).

func (*SoftwareRenderer) SetFrameHooks

func (r *SoftwareRenderer) SetFrameHooks(beforePass, afterFrame func(frameIndex uint64, frameSlot int))

SetFrameHooks installs optional callbacks invoked on the GPU execution thread immediately before render passes execute and immediately after each frame finishes (before signaling the frame's FrameFence).

func (*SoftwareRenderer) SetPipelined

func (r *SoftwareRenderer) SetPipelined(enabled bool)

SetPipelined enables or disables background GPU-worker execution on the software renderer so CPU frame N+1 ring-buffer writes overlap with GPU frame N rasterization, synchronized by FrameFence.

func (*SoftwareRenderer) WaitIdle

func (r *SoftwareRenderer) WaitIdle()

WaitIdle blocks until all queued pipelined frames have completed.

type StencilFaceState

type StencilFaceState struct {
	Compare     CompareFunc      // CompareUndefined defaults to CompareAlways
	FailOp      StencilOperation // applied when the stencil test fails
	DepthFailOp StencilOperation // applied when stencil passes and depth fails
	PassOp      StencilOperation // applied when both stencil and depth pass
}

StencilFaceState configures stencil comparison and update operations for one winding face.

type StencilOperation

type StencilOperation uint8

StencilOperation specifies how a stencil buffer value updates after stencil/depth testing.

type StoreOp

type StoreOp uint8

StoreOp selects whether an attachment's contents are stored at the end of a RenderPass.

const (
	StoreStore   StoreOp = StoreOp(driver.GPUStoreStore)
	StoreDiscard StoreOp = StoreOp(driver.GPUStoreDiscard)
)

type Texture

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

Texture is a retained GPU 2D, cube, array, or depth texture.

func (*Texture) Close

func (t *Texture) Close() error

Close releases the texture immediately.

func (*Texture) Desc

func (t *Texture) Desc() TextureDesc

Desc returns the texture's descriptor.

func (*Texture) Epoch

func (t *Texture) Epoch() uint32

Epoch returns the device epoch this texture currently belongs to.

func (*Texture) ID

func (t *Texture) ID() uint64

ID returns the texture's numeric handle.

func (*Texture) Imported

func (t *Texture) Imported() bool

Imported reports whether t was opened by Device.ImportTexture.

func (*Texture) Valid

func (t *Texture) Valid() bool

Valid reports whether t is open and bound to a live device at its current epoch.

type TextureCopy

type TextureCopy struct {
	Texture    *Texture
	MipLevel   uint32
	ArrayLayer uint32
	OriginX    uint32
	OriginY    uint32
}

TextureCopy identifies a texture subresource and origin for writes and copies.

type TextureDesc

type TextureDesc struct {
	Label       string
	Dimension   TextureDimension
	Width       uint32
	Height      uint32
	Layers      uint32 // 0 or 1 for 2D, 6 for Cube, N for 2DArray
	MipLevels   uint32 // 0 defaults to 1
	SampleCount int    // 0 or 1; 4 for MSAA render attachments
	Format      TextureFormat
	Usage       TextureUsage
	Retained    bool // opt in to automatic recreation with latest writes after device loss
}

TextureDesc configures Device.CreateTexture.

type TextureDimension

type TextureDimension uint8

TextureDimension is the dimensionality of a Texture.

type TextureFormat

type TextureFormat uint8

TextureFormat identifies the pixel or depth/stencil layout of a Texture.

const (
	FormatUndefined           TextureFormat = TextureFormat(driver.GPUFormatUndefined)
	FormatRGBA8Unorm          TextureFormat = TextureFormat(driver.GPUFormatRGBA8Unorm)
	FormatRGBA8UnormSRGB      TextureFormat = TextureFormat(driver.GPUFormatRGBA8UnormSRGB)
	FormatBGRA8Unorm          TextureFormat = TextureFormat(driver.GPUFormatBGRA8Unorm)
	FormatRG8Unorm            TextureFormat = TextureFormat(driver.GPUFormatRG8Unorm)
	FormatR8Unorm             TextureFormat = TextureFormat(driver.GPUFormatR8Unorm)
	FormatRGBA16Float         TextureFormat = TextureFormat(driver.GPUFormatRGBA16Float)
	FormatDepth24Plus         TextureFormat = TextureFormat(driver.GPUFormatDepth24Plus)
	FormatDepth24PlusStencil8 TextureFormat = TextureFormat(driver.GPUFormatDepth24PlusStencil8)
	FormatDepth32Float        TextureFormat = TextureFormat(driver.GPUFormatDepth32Float)
	FormatBC1RGBAUnorm        TextureFormat = TextureFormat(driver.GPUFormatBC1RGBAUnorm)
	FormatBC1RGBAUnormSRGB    TextureFormat = TextureFormat(driver.GPUFormatBC1RGBAUnormSRGB)
	FormatBC3RGBAUnorm        TextureFormat = TextureFormat(driver.GPUFormatBC3RGBAUnorm)
	FormatBC3RGBAUnormSRGB    TextureFormat = TextureFormat(driver.GPUFormatBC3RGBAUnormSRGB)
	FormatBC7RGBAUnorm        TextureFormat = TextureFormat(driver.GPUFormatBC7RGBAUnorm)
	FormatBC7RGBAUnormSRGB    TextureFormat = TextureFormat(driver.GPUFormatBC7RGBAUnormSRGB)
	FormatETC2RGB8Unorm       TextureFormat = TextureFormat(driver.GPUFormatETC2RGB8Unorm)
	FormatETC2RGBA8Unorm      TextureFormat = TextureFormat(driver.GPUFormatETC2RGBA8Unorm)
	FormatASTC4x4Unorm        TextureFormat = TextureFormat(driver.GPUFormatASTC4x4Unorm)
	FormatASTC4x4UnormSRGB    TextureFormat = TextureFormat(driver.GPUFormatASTC4x4UnormSRGB)

	// Extended formats: accepted only where Features.ExtendedFormats is set (Device.SupportsFormat).
	FormatBGRA8UnormSRGB TextureFormat = TextureFormat(driver.GPUFormatBGRA8UnormSRGB)
	FormatRG11B10Float   TextureFormat = TextureFormat(driver.GPUFormatRG11B10Float)
	FormatR32Float       TextureFormat = TextureFormat(driver.GPUFormatR32Float)
	FormatRGBA32Float    TextureFormat = TextureFormat(driver.GPUFormatRGBA32Float)
	FormatStencil8       TextureFormat = TextureFormat(driver.GPUFormatStencil8)

	// Import-only formats: textures from Device.ImportTexture, such as the planes of a P010 frame, have them; Device.CreateTexture does not take them.
	FormatR16Unorm  TextureFormat = TextureFormat(driver.GPUFormatR16Unorm)
	FormatRG16Unorm TextureFormat = TextureFormat(driver.GPUFormatRG16Unorm)

	// Short HDR float format aliases matching WGSL/shader shorthand.
	FormatRGBA16F  TextureFormat = FormatRGBA16Float
	FormatRG11B10F TextureFormat = FormatRG11B10Float
	FormatR32F     TextureFormat = FormatR32Float
	FormatRGBA32F  TextureFormat = FormatRGBA32Float
)

func (TextureFormat) BlockSize

func (f TextureFormat) BlockSize() (width, height uint32)

BlockSize returns the compression block dimensions (width, height) in texels. Uncompressed formats return (1, 1); FormatUndefined returns (0, 0).

func (TextureFormat) ByteSize

func (f TextureFormat) ByteSize(width, height uint32) uint64

ByteSize returns the tightly-packed byte size of a 2D texture level of width x height texels in format f.

func (TextureFormat) BytesPerBlock

func (f TextureFormat) BytesPerBlock() uint32

BytesPerBlock returns the byte size of one texel block (or one texel for uncompressed color formats; 0 for depth or undefined formats).

func (TextureFormat) HasStencil

func (f TextureFormat) HasStencil() bool

HasStencil reports whether f carries a stencil aspect.

func (TextureFormat) IsCompressed

func (f TextureFormat) IsCompressed() bool

IsCompressed reports whether f is a block-compressed texture format (BCn, ETC2, ASTC).

func (TextureFormat) IsDepth

func (f TextureFormat) IsDepth() bool

IsDepth reports whether f carries a depth aspect.

func (TextureFormat) IsDepthStencil

func (f TextureFormat) IsDepthStencil() bool

IsDepthStencil reports whether f is a depth, stencil, or depth-stencil format.

func (TextureFormat) IsFloat

func (f TextureFormat) IsFloat() bool

IsFloat reports whether f is a floating-point color format (HDR/unclamped).

func (TextureFormat) IsSRGB

func (f TextureFormat) IsSRGB() bool

IsSRGB reports whether f decodes sRGB RGB channels to linear on texture sampling.

func (TextureFormat) String

func (f TextureFormat) String() string

String returns the format's canonical name.

type TextureRegion

type TextureRegion struct {
	MipLevel   uint32
	ArrayLayer uint32
	X, Y       uint32
	Width      uint32
	Height     uint32
}

TextureRegion selects a rectangular region for Device.ReadTexture.

type TextureUsage

type TextureUsage uint32

TextureUsage is a bitmask of permitted uses for a Texture.

type TextureWrite

type TextureWrite struct {
	Texture    *Texture
	MipLevel   uint32
	ArrayLayer uint32
	OriginX    uint32
	OriginY    uint32
	Width      uint32 // 0 defaults to mipWidth - OriginX
	Height     uint32 // 0 defaults to mipHeight - OriginY
}

TextureWrite identifies a texture subresource (mip level, array layer or cubemap face, and optional sub-rectangle) for Device.WriteTextureRegion.

type TimestampQuery

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

TimestampQuery collects per-pass GPU timing measurements for render passes that reference it via RenderPassDesc.TimestampQuery.

func (*TimestampQuery) Close

func (q *TimestampQuery) Close() error

Close releases the timestamp query. Safe to call more than once.

func (*TimestampQuery) ID

func (q *TimestampQuery) ID() uint64

ID returns the query's numeric handle.

func (*TimestampQuery) Label

func (q *TimestampQuery) Label() string

Label returns the query's default timing label.

func (*TimestampQuery) LastDuration

func (q *TimestampQuery) LastDuration() time.Duration

LastDuration returns the most recently recorded pass duration, or 0 if none.

func (*TimestampQuery) Reset

func (q *TimestampQuery) Reset()

Reset clears previously accumulated timing entries from q.

func (*TimestampQuery) Timings

func (q *TimestampQuery) Timings() []PassTiming

Timings returns a copy of all completed pass timings recorded into q.

type VertexAttribute

type VertexAttribute struct {
	Format   VertexFormat
	Offset   uint64
	Location uint32
}

VertexAttribute describes one attribute inside a VertexBufferLayout.

type VertexBufferLayout

type VertexBufferLayout struct {
	Stride     uint64
	StepMode   VertexStepMode
	StepRate   uint32 // 0 defaults to 1 when StepMode is StepInstance / VertexStepInstance
	Attributes []VertexAttribute
}

VertexBufferLayout describes one vertex buffer slot of a Pipeline.

type VertexStepMode

type VertexStepMode uint8

VertexStepMode selects whether a vertex buffer advances per vertex or per instance.

type ViewProps

type ViewProps struct {
	// ColorFormat defaults to the platform's preferred swapchain format.
	ColorFormat TextureFormat
	// DepthFormat enables an automatic swapchain depth/stencil buffer resized
	// with the view (e.g. FormatDepth24Plus). FormatUndefined disables it.
	DepthFormat TextureFormat
	// SampleCount is 1 (default) or 4 for swapchain MSAA.
	SampleCount int
	// FramesInFlight configures the number of rotating per-frame ring-buffer
	// slots (2 or 3). Zero defaults to DefaultFramesInFlight (2); values outside
	// [MinFramesInFlight, MaxFramesInFlight] are clamped cleanly to [2, 3].
	FramesInFlight int

	// OnReady runs on the engine goroutine when the GPU device and surface are
	// ready, and again after recovery from device loss.
	OnReady func(dev *Device)
	// OnFrame, when set, runs on every display frame via RequestAnimationFrame
	// once the device is ready and not suspended, submitting commands off-commit with zero UI view-tree commits per frame.
	OnFrame func(frame *Frame)
	// OnResize runs when the drawable size in physical pixels changes.
	OnResize func(width, height int)
	// OnDeviceLost runs if the underlying GPU context or device is lost; all
	// non-retained handles from the previous Device are invalidated.
	OnDeviceLost func(DeviceLostEvent)
	// OnDeviceRestored runs on the engine goroutine after a lost device or surface is recreated, receiving the fresh ready *Device after any retained resources have been automatically restored.
	OnDeviceRestored func(dev *Device)
	// OnSuspend runs when the app or surface enters the background and GPU frame submission is automatically paused.
	OnSuspend func()
	// OnResume runs when the app or surface returns to the active state and GPU frame submission resumes.
	OnResume func()
	// OnError reports asynchronous GPU validation, unsupported, or OOM errors.
	OnError func(Error)
	// OnPassTimings runs on the engine goroutine when per-pass GPU timing measurements complete for a submitted frame.
	OnPassTimings func([]PassTiming)

	// RetainResources, when true, opts every resource created on this view's Device into automatic recreation after device or surface loss.
	RetainResources bool
	// PipelineCache, when set, attaches a persistent pipeline cache to every Device created by this view (including restored devices).
	PipelineCache *PipelineCache

	Class     string
	Style     core.Style
	StyleFunc func() core.Style
	Children  []core.Node
	OnPress   func(core.PressEvent)
	OnLayout  func(core.Bounds)
	Ref       *core.Ref
	Label     string
	LabelFunc func() string
	TestID    string
}

ViewProps configures a GPU-backed 3D surface mounted in the NSGo view tree. Children render over the GPU surface as ordinary native NSGo views (HUD, menus).

func (ViewProps) Render

func (p ViewProps) Render(cx *core.Scope) core.Node

Render implements core.Node so ViewProps may be returned directly as a node or wrapped via gpu.View(cx, props).

Jump to

Keyboard shortcuts

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