shader

package
v0.27.0 Latest Latest
Warning

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

Go to latest
Published: May 6, 2026 License: MIT Imports: 8 Imported by: 0

Documentation

Overview

Package shader provides shader execution for the software backend.

Two execution paths are supported:

  • SPIR-V interpreter: parses and executes SPIR-V bytecode (compiled from WGSL via naga). This enables rendering shaders that use @builtin(vertex_index) with no vertex buffers (e.g. the gogpu triangle example). See Module, ParseModule, and Module.Execute.

  • Callback shaders: Go functions implementing VertexShaderFunc / FragmentShaderFunc for programmatic shader definition without SPIR-V. Useful for testing and built-in effects (solid color, vertex color, textured).

Shader Types

There are two main shader stages:

  • Vertex Shader: Transforms vertices from object space to clip space. Receives vertex position and attributes, outputs clip-space position and interpolated attributes.

  • Fragment Shader: Computes the final color for each fragment (pixel candidate). Receives interpolated fragment data and outputs RGBA color.

Built-in Shaders

The package provides several built-in shaders for common use cases:

  • SolidColor: Renders geometry with a uniform color.
  • VertexColor: Interpolates per-vertex colors across the triangle.

Usage

// Create a shader program
program := shader.ShaderProgram{
    Vertex:   shader.SolidColorVertexShader,
    Fragment: shader.SolidColorFragmentShader,
}

// Prepare uniforms
uniforms := &shader.SolidColorUniforms{
    MVP:   myMVPMatrix,
    Color: [4]float32{1, 0, 0, 1}, // Red
}

// Use with the rasterization pipeline
// (integration code varies based on pipeline implementation)

Custom Shaders

To create custom shaders, implement the VertexShaderFunc and FragmentShaderFunc signatures:

func MyVertexShader(
    vertexIndex int,
    position [3]float32,
    attributes []float32,
    uniforms any,
) raster.ClipSpaceVertex {
    // Transform position and prepare attributes
}

func MyFragmentShader(
    fragment raster.Fragment,
    uniforms any,
) [4]float32 {
    // Compute and return RGBA color
}

Index

Constants

View Source
const (
	GLSLRound     = 1
	GLSLRoundEven = 2
	GLSLTrunc     = 3
	GLSLFAbs      = 4
	GLSLSAbs      = 5
	GLSLFSign     = 6
	GLSLSSign     = 7
	GLSLFloor     = 8
	GLSLCeil      = 9
	GLSLFract     = 10

	GLSLSin  = 13
	GLSLCos  = 14
	GLSLTan  = 15
	GLSLAsin = 16
	GLSLAcos = 17
	GLSLAtan = 18

	GLSLPow         = 26
	GLSLExp         = 27
	GLSLLog         = 28
	GLSLExp2        = 29
	GLSLLog2        = 30
	GLSLSqrt        = 31
	GLSLInverseSqrt = 32

	GLSLFMin   = 37
	GLSLUMin   = 38
	GLSLSMin   = 39
	GLSLFMax   = 40
	GLSLUMax   = 41
	GLSLSMax   = 42
	GLSLFClamp = 43

	GLSLFMix       = 46
	GLSLStep       = 48
	GLSLSmoothStep = 49

	GLSLAtan2 = 25

	GLSLLength    = 66
	GLSLDistance  = 67
	GLSLCross     = 68
	GLSLNormalize = 69
	GLSLReflect   = 71

	GLSLDeterminant   = 76
	GLSLMatrixInverse = 77
)

GLSL.std.450 instruction numbers. Reference: SPIR-V Extended Instructions for GLSL, section 2.

View Source
const (
	OpNop                  = 0
	OpExtInstImport        = 11
	OpMemoryModel          = 14
	OpEntryPoint           = 15
	OpExecutionMode        = 16
	OpCapability           = 17
	OpTypeVoid             = 19
	OpTypeBool             = 20
	OpTypeInt              = 21
	OpTypeFloat            = 22
	OpTypeVector           = 23
	OpTypeArray            = 28
	OpTypeRuntimeArray     = 29
	OpTypeStruct           = 30
	OpTypePointer          = 32
	OpTypeFunction         = 33
	OpConstant             = 43
	OpConstantComposite    = 44
	OpConstantNull         = 46
	OpFunction             = 54
	OpFunctionParameter    = 55
	OpFunctionEnd          = 56
	OpVariable             = 59
	OpLoad                 = 61
	OpStore                = 62
	OpAccessChain          = 65
	OpDecorate             = 71
	OpMemberDecorate       = 72
	OpCompositeExtract     = 81
	OpCompositeConstruct   = 80
	OpReturn               = 253
	OpReturnValue          = 254
	OpLabel                = 248
	OpBranch               = 249
	OpSource               = 3
	OpSourceExtension      = 4
	OpName                 = 5
	OpMemberName           = 6
	OpString               = 7
	OpLine                 = 8
	OpNoLine               = 317
	OpModuleProcessed      = 330
	OpUndef                = 1
	OpExtInst              = 12
	OpBitcast              = 124
	OpConvertUToF          = 112
	OpConvertFToU          = 109
	OpConvertSToF          = 111
	OpIAdd                 = 128
	OpISub                 = 130
	OpIMul                 = 132
	OpFAdd                 = 129
	OpFSub                 = 131
	OpFMul                 = 133
	OpFDiv                 = 136
	OpSDiv                 = 135
	OpUDiv                 = 134
	OpFNegate              = 127
	OpSelect               = 169
	OpBranchConditional    = 250
	OpSelectionMerge       = 247
	OpLoopMerge            = 246
	OpPhi                  = 245
	OpIEqual               = 170
	OpINotEqual            = 171
	OpFOrdEqual            = 180
	OpFOrdLessThan         = 184
	OpFOrdGreaterThan      = 186
	OpFOrdLessThanEqual    = 188
	OpFOrdGreaterThanEqual = 190

	// Additional opcodes for Phases 2-6.
	OpDot               = 148
	OpVectorTimesScalar = 142
	OpMatrixTimesVector = 145
	OpMatrixTimesScalar = 143
	OpMatrixTimesMatrix = 146
	OpTranspose         = 84
	OpVectorShuffle     = 79

	OpFunctionCall = 57

	OpSwitch      = 251
	OpKill        = 252
	OpUnreachable = 255

	// Comparison ops (integer, unsigned).
	OpULessThan         = 176
	OpUGreaterThan      = 172
	OpULessThanEqual    = 178
	OpUGreaterThanEqual = 174
	OpSLessThan         = 177
	OpSGreaterThan      = 173
	OpSLessThanEqual    = 179
	OpSGreaterThanEqual = 175

	// Logical ops.
	OpLogicalAnd = 167
	OpLogicalOr  = 166
	OpLogicalNot = 168

	// Bitwise ops.
	OpBitwiseAnd           = 199
	OpBitwiseOr            = 197
	OpBitwiseXor           = 198
	OpNot                  = 200
	OpShiftLeftLogical     = 196
	OpShiftRightLogical    = 194
	OpShiftRightArithmetic = 195

	// Image / sampler ops.
	OpTypeImage              = 25
	OpTypeSampler            = 26
	OpTypeSampledImage       = 27
	OpSampledImage           = 86
	OpImageSampleImplicitLod = 87
	OpImageSampleExplicitLod = 88
	OpImageFetch             = 95
	OpImageQuerySize         = 104

	// Atomic ops.
	OpAtomicLoad            = 227
	OpAtomicStore           = 228
	OpAtomicExchange        = 229
	OpAtomicCompareExchange = 230
	OpAtomicIIncrement      = 232
	OpAtomicIDecrement      = 233
	OpAtomicIAdd            = 234
	OpAtomicISub            = 235
	OpAtomicSMin            = 236
	OpAtomicUMin            = 237
	OpAtomicSMax            = 238
	OpAtomicUMax            = 239

	// Barrier ops.
	OpControlBarrier = 224
	OpMemoryBarrier  = 225

	// Type conversion ops.
	OpConvertFToS = 110
	OpSConvert    = 114
	OpUConvert    = 113
	OpFConvert    = 115

	// Misc ops.
	OpCopyObject = 83
	OpFMod       = 141
	OpSMod       = 139
	OpUMod       = 137
	OpSRem       = 138
	OpFRem       = 140
	OpSNegate    = 126

	// Constant ops.
	OpConstantTrue      = 41
	OpConstantFalse     = 42
	OpSpecConstant      = 48
	OpSpecConstantTrue  = 49
	OpSpecConstantFalse = 50

	// Image operand masks.
	ImageOperandBiasMask = 0x1
	ImageOperandLodMask  = 0x2
	ImageOperandGradMask = 0x4
)

SPIR-V opcodes relevant to the triangle shader. Reference: SPIR-V Specification v1.6, section 3.32 (Instructions).

View Source
const (
	StorageClassUniformConstant = 0
	StorageClassInput           = 1
	StorageClassUniform         = 2
	StorageClassOutput          = 3
	StorageClassWorkgroup       = 4
	StorageClassCrossWorkgroup  = 5
	StorageClassPrivate         = 6
	StorageClassFunction        = 7
	StorageClassGeneric         = 8
	StorageClassPushConstant    = 9
	StorageClassAtomicCounter   = 10
	StorageClassImage           = 11
	StorageClassStorageBuffer   = 12
)

SPIR-V storage classes.

View Source
const (
	DecorationArrayStride   = 6
	DecorationBuiltIn       = 11
	DecorationBinding       = 33
	DecorationDescriptorSet = 34
	DecorationLocation      = 30
	DecorationOffset        = 35
	DecorationBlock         = 2
	DecorationBufferBlock   = 3
	DecorationColMajor      = 5
	DecorationMatrixStride  = 7
	DecorationNonWritable   = 24
	DecorationNonReadable   = 25
)

SPIR-V decoration constants.

View Source
const (
	BuiltInPosition           = 0
	BuiltInPointSize          = 1
	BuiltInVertexIndex        = 42
	BuiltInInstanceIndex      = 43
	BuiltInFragCoord          = 15
	BuiltInFrontFacing        = 17
	BuiltInSampleID           = 18
	BuiltInSampleMask         = 20
	BuiltInFragDepth          = 22
	BuiltInGlobalInvocationID = 28
	BuiltInLocalInvocationID  = 27
	BuiltInWorkgroupID        = 26
	BuiltInNumWorkgroups      = 24
	BuiltInLocalInvocationIdx = 29
	BuiltInWorkgroupSize      = 25
)

SPIR-V BuiltIn values.

View Source
const (
	ExecutionModelVertex    = 0
	ExecutionModelFragment  = 4
	ExecutionModelGLCompute = 5
)

SPIR-V execution model constants.

View Source
const (
	WrapRepeat         = 0
	WrapClampToEdge    = 1
	WrapMirroredRepeat = 2
)

Wrap mode constants.

View Source
const (
	FilterNearest = 0
	FilterLinear  = 1
)

Filter constants.

View Source
const (
	ExecutionModeLocalSize = 17
)

Execution mode constants.

Variables

This section is empty.

Functions

func BarycentricFragmentShader

func BarycentricFragmentShader(fragment raster.Fragment, _ any) [4]float32

BarycentricFragmentShader returns a color based on barycentric coordinates. Useful for debugging triangle rasterization.

func DepthFragmentShader

func DepthFragmentShader(fragment raster.Fragment, _ any) [4]float32

DepthFragmentShader returns a grayscale color based on fragment depth. Useful for visualizing the depth buffer.

func Float32BitsToUint32 added in v0.27.0

func Float32BitsToUint32(f float32) uint32

Float32BitsToUint32 converts a float32 to its bit representation as uint32. Used for SPIR-V constant encoding in tests.

func Mat4Identity

func Mat4Identity() [16]float32

Mat4Identity returns a 4x4 identity matrix.

func Mat4Mul

func Mat4Mul(a, b [16]float32) [16]float32

Mat4Mul multiplies two 4x4 matrices (column-major order).

func Mat4MulVec4

func Mat4MulVec4(m [16]float32, v [4]float32) [4]float32

Mat4MulVec4 multiplies a 4x4 matrix by a vec4 (column-major order). This is the standard OpenGL/WebGPU matrix-vector multiplication.

func Mat4Ortho

func Mat4Ortho(left, right, bottom, top, near, far float32) [16]float32

Mat4Ortho creates an orthographic projection matrix. Parameters define the view volume: left, right, bottom, top, near, far.

func Mat4Scale

func Mat4Scale(x, y, z float32) [16]float32

Mat4Scale creates a scale matrix.

func Mat4Translate

func Mat4Translate(x, y, z float32) [16]float32

Mat4Translate creates a translation matrix.

func PassthroughVertexShader

func PassthroughVertexShader(
	vertexIndex int,
	position [3]float32,
	attributes []float32,
	_ any,
) raster.ClipSpaceVertex

PassthroughVertexShader is a simple vertex shader that passes position through without transformation. Useful for screen-space rendering.

func SolidColorFragmentShader

func SolidColorFragmentShader(frag raster.Fragment, _ any) [4]float32

SolidColorFragmentShader returns the uniform color for all fragments.

func SolidColorVertexShader

func SolidColorVertexShader(
	_ int,
	position [3]float32,
	_ []float32,
	uniforms any,
) raster.ClipSpaceVertex

SolidColorVertexShader transforms vertices using the MVP matrix. The color is passed through as attributes for the fragment shader.

func TexturedFragmentShader

func TexturedFragmentShader(frag raster.Fragment, uniforms any) [4]float32

TexturedFragmentShader samples a texture using interpolated UV coordinates.

func TexturedVertexShader

func TexturedVertexShader(
	_ int,
	position [3]float32,
	attributes []float32,
	uniforms any,
) raster.ClipSpaceVertex

TexturedVertexShader transforms vertices and passes UV coordinates as attributes. Expects attrs[0:2] to be UV coordinates.

func Vec4ToFloat32 added in v0.27.0

func Vec4ToFloat32(val Value) [4]float32

Vec4ToFloat32 extracts a Vec4 from a Value, returning zeros if type doesn't match.

func VertexColorFragmentShader

func VertexColorFragmentShader(frag raster.Fragment, _ any) [4]float32

VertexColorFragmentShader returns the interpolated vertex color.

func VertexColorVertexShader

func VertexColorVertexShader(
	_ int,
	position [3]float32,
	attributes []float32,
	uniforms any,
) raster.ClipSpaceVertex

VertexColorVertexShader transforms vertices and passes vertex colors as attributes. Expects attrs[0:4] to be RGBA color values in [0, 1].

func WhiteFragmentShader

func WhiteFragmentShader(_ raster.Fragment, _ any) [4]float32

WhiteFragmentShader returns white for all fragments. Useful for testing and debugging.

Types

type Array added in v0.27.0

type Array = []Value

Type aliases kept for backward compatibility with external code and tests. These are the underlying Go types used for construction only.

type BindingKey added in v0.27.0

type BindingKey struct {
	Group   uint32
	Binding uint32
}

BindingKey identifies a resource binding by descriptor set and binding number.

type BufferPointer added in v0.27.0

type BufferPointer struct {
	Buffer []byte    // raw buffer data
	Offset uint32    // byte offset within the buffer
	Type   *TypeInfo // type of the pointed-to element
}

BufferPointer provides direct read/write access to a position within a raw byte buffer. Used for storage buffer access chains where OpStore must write back to the buffer.

type DebugAction added in v0.27.0

type DebugAction int

DebugAction controls execution flow after a debug callback.

const (
	// DebugContinue resumes execution until the next breakpoint or watch trigger.
	DebugContinue DebugAction = iota

	// DebugStep executes one instruction, then fires the OnInstruction callback.
	DebugStep

	// DebugAbort stops execution immediately. ExecuteWithDebug returns
	// a nil output map and an ErrDebugAbort error.
	DebugAbort
)

type DebugContext added in v0.27.0

type DebugContext struct {
	// OnInstruction is called before each instruction executes (when stepping
	// or when a watched variable changed). The returned DebugAction controls
	// whether to continue, step, or abort.
	OnInstruction func(event InstructionEvent) DebugAction

	// OnBreakpoint is called when execution reaches a breakpoint instruction
	// index. If both OnBreakpoint and OnInstruction are set, OnBreakpoint fires
	// first, then OnInstruction fires and its return value controls flow.
	OnBreakpoint func(event InstructionEvent)

	// OnError is called when an instruction produces a runtime error (e.g.,
	// exceeding max iterations). The error is still returned from ExecuteWithDebug.
	OnError func(event ErrorEvent)

	// Breakpoints maps instruction index (0-based within the function) to
	// a boolean indicating whether a breakpoint is set. The instruction at
	// the given index triggers the OnBreakpoint callback before execution.
	Breakpoints map[int]bool

	// WatchVariables maps SSA result IDs to watch status. When a watched
	// variable's value changes after an instruction, OnInstruction is called
	// with DebugStep regardless of breakpoints.
	WatchVariables map[uint32]bool

	// TraceEnabled enables JSON-lines trace output. Each instruction that
	// produces a result writes one JSON line to TraceWriter after execution.
	TraceEnabled bool

	// TraceWriter receives JSON-lines trace output when TraceEnabled is true.
	// Each line is a self-contained JSON object terminated by a newline.
	TraceWriter io.Writer
}

DebugContext configures shader debugging for a single ExecuteWithDebug call.

All fields are optional. When DebugContext is nil, the interpreter runs at full speed with zero debug overhead.

type EntryPoint added in v0.27.0

type EntryPoint struct {
	ExecutionModel uint32
	FunctionID     uint32
	Name           string
	InterfaceIDs   []uint32 // IDs of interface variables
}

EntryPoint describes a SPIR-V entry point.

type ErrorEvent added in v0.27.0

type ErrorEvent struct {
	// PC is the instruction index where the error occurred.
	PC int

	// Instruction is the instruction that caused the error.
	Instruction Instruction

	// Err is the runtime error.
	Err error
}

ErrorEvent provides information about a runtime error during debug execution.

type ExecutionContext added in v0.27.0

type ExecutionContext struct {
	// Inputs maps variable ID to its value (builtin inputs like vertex_index).
	Inputs map[uint32]Value

	// Buffers maps (group, binding) to raw buffer data for uniform/storage buffers.
	Buffers map[BindingKey][]byte

	// Textures maps (group, binding) to a 2D texture.
	Textures map[BindingKey]*Texture2D

	// Samplers maps (group, binding) to sampler parameters.
	Samplers map[BindingKey]*Sampler

	// WorkgroupSharedMemory is shared memory for compute shader workgroups.
	// Maps variable ID to a byte slice shared across all invocations.
	WorkgroupSharedMemory map[uint32][]byte

	// ComputeBuiltins provides compute shader built-in values.
	GlobalInvocationID   [3]uint32
	LocalInvocationID    [3]uint32
	WorkgroupID          [3]uint32
	NumWorkgroups        [3]uint32
	WorkgroupSize        [3]uint32
	LocalInvocationIndex uint32
}

ExecutionContext provides bound resources for shader execution. Shaders read uniform/storage buffers, textures, and samplers through this context.

type Float32 added in v0.27.0

type Float32 = float32

Type aliases kept for backward compatibility with external code and tests. These are the underlying Go types used for construction only.

type FragmentShaderFunc

type FragmentShaderFunc func(
	fragment raster.Fragment,
	uniforms any,
) [4]float32

FragmentShaderFunc computes the final color for a fragment. It receives interpolated fragment data and returns an RGBA color.

Parameters:

  • fragment: The fragment with interpolated position, depth, and attributes.
  • uniforms: User-defined uniform data (textures, colors, etc.).

Returns:

  • [4]float32: RGBA color values in the range [0, 1].

type Function added in v0.27.0

type Function struct {
	ID           uint32
	ReturnType   uint32
	FunctionType uint32
	Instructions []Instruction

	// Labels maps label ID to instruction index. Built once during ParseModule
	// to avoid rebuilding on every Execute call. OpBranch and OpBranchConditional
	// use this for control flow.
	Labels map[uint32]int
}

Function is a parsed SPIR-V function body.

type Instruction added in v0.27.0

type Instruction struct {
	Opcode   uint16
	ResultID uint32   // 0 if instruction produces no result
	TypeID   uint32   // 0 if instruction has no result type
	Operands []uint32 // remaining operands after result/type
}

Instruction represents a decoded SPIR-V instruction.

type InstructionEvent added in v0.27.0

type InstructionEvent struct {
	// PC is the 0-based instruction index within the current function.
	PC int

	// Instruction is the SPIR-V instruction about to execute (for OnInstruction
	// and OnBreakpoint) or just executed (for watch triggers).
	Instruction Instruction

	// Values is the current SSA value slice indexed by SPIR-V ID. This is a
	// direct reference to the interpreter's live values -- callers should
	// treat it as read-only.
	Values []Value

	// BlockLabel is the result ID of the current basic block's OpLabel.
	BlockLabel uint32
}

InstructionEvent provides information about the current instruction during a debug callback. The Values slice is a read-only snapshot -- modifications are ignored by the interpreter.

type Int32 added in v0.27.0

type Int32 = int32

Type aliases kept for backward compatibility with external code and tests. These are the underlying Go types used for construction only.

type Mat4 added in v0.27.0

type Mat4 = [4]Vec4

Mat4 is a 4x4 column-major matrix stored as an Array of 4 Vec4 columns. SPIR-V represents matrices as arrays of column vectors.

type Module added in v0.27.0

type Module struct {
	// Types maps result ID to type information.
	Types map[uint32]*TypeInfo

	// Constants maps result ID to constant value.
	Constants map[uint32]Value

	// Functions maps entry point name to function body.
	Functions map[string]*Function

	// EntryPoints maps entry point name to its metadata.
	EntryPoints map[string]*EntryPoint

	// Decorations maps (target ID, decoration kind) to decoration value.
	Decorations map[decorationKey]uint32

	// MemberDecorations maps (struct type ID, member index, decoration kind) to value.
	// Used for OpMemberDecorate, primarily for struct member Offset decorations.
	MemberDecorations map[memberDecorationKey]uint32

	// Variables maps result ID to variable metadata.
	Variables map[uint32]*VariableInfo

	// FunctionsByID maps function result ID to function body.
	// Used by OpFunctionCall to dispatch to non-entry-point functions.
	FunctionsByID map[uint32]*Function

	// ExtInstImports maps result ID to the imported instruction set name.
	// The primary use is "GLSL.std.450" for math intrinsics.
	ExtInstImports map[uint32]string

	// ExecutionModes maps (function ID, execution mode) to operands.
	// Used for LocalSize in compute shaders.
	ExecutionModes map[executionModeKey][]uint32

	// Bound is the upper bound of all IDs in the module.
	Bound uint32
	// contains filtered or unexported fields
}

Module is a parsed SPIR-V module ready for interpretation.

func ParseModule added in v0.27.0

func ParseModule(words []uint32) (*Module, error)

ParseModule parses SPIR-V binary (as []uint32 words) into a Module.

The SPIR-V format is: 5-word header (magic, version, generator, bound, reserved) followed by a stream of instructions. Each instruction's first word encodes (wordCount << 16 | opcode).

func (*Module) DispatchCompute added in v0.27.0

func (m *Module) DispatchCompute(entryPoint string, ctx *ExecutionContext,
	groupCountX, groupCountY, groupCountZ uint32) error

DispatchCompute executes a compute shader for all invocations in the dispatch. groupCountX/Y/Z specify the number of workgroups to dispatch. The entry point's LocalSize execution mode determines the workgroup dimensions.

This is a single-threaded execution: invocations run sequentially within each workgroup. OpControlBarrier is a no-op since there is no true parallelism.

func (*Module) Execute added in v0.27.0

func (m *Module) Execute(entryPoint string, inputs map[uint32]Value) (map[uint32]Value, error)

Execute runs the named entry point with the given input variable values.

inputs maps variable ID (decorated with BuiltIn or Location) to its value. Returns a map of output variable ID to its value after execution.

For a vertex shader, inputs typically contain:

  • vertex_index variable ID -> Uint32 value

Outputs typically contain:

  • position variable ID -> Vec4 value

func (*Module) ExecuteCompute added in v0.27.0

func (m *Module) ExecuteCompute(entryPoint string, ctx *ExecutionContext) error

ExecuteCompute runs a compute shader entry point for a single invocation.

The context must have ComputeBuiltins (GlobalInvocationID, LocalInvocationID, WorkgroupID, NumWorkgroups, WorkgroupSize, LocalInvocationIndex) populated by the caller for each invocation.

Storage buffer writes are reflected in the context's Buffers map.

func (*Module) ExecuteWithContext added in v0.27.0

func (m *Module) ExecuteWithContext(entryPoint string, ctx *ExecutionContext) (map[uint32]Value, error)

ExecuteWithContext runs the named entry point with full resource context. The context provides bound buffers, textures, and samplers for the shader.

func (*Module) ExecuteWithDebug added in v0.27.0

func (m *Module) ExecuteWithDebug(entryPoint string, ctx *ExecutionContext, debug *DebugContext) (map[uint32]Value, error)

ExecuteWithDebug runs the named entry point with full resource context and optional debug support. When debug is nil, execution proceeds at full speed with zero overhead -- the existing Execute and ExecuteWithContext methods call this with debug=nil.

When debug is non-nil, the interpreter fires callbacks for breakpoints, variable watches, and instruction tracing. See DebugContext for details.

func (*Module) GetBinding added in v0.27.0

func (m *Module) GetBinding(varID uint32) (BindingKey, bool)

GetBinding returns the (group, binding) for a variable, or ok=false if not decorated.

func (*Module) GetBuiltIn added in v0.27.0

func (m *Module) GetBuiltIn(varID uint32) int

GetBuiltIn returns the BuiltIn decoration value for a variable ID, or -1 if none.

func (*Module) GetLocation added in v0.27.0

func (m *Module) GetLocation(varID uint32) int

GetLocation returns the Location decoration value for a variable ID, or -1 if none.

func (*Module) GetMemberOffset added in v0.27.0

func (m *Module) GetMemberOffset(structTypeID, memberIndex uint32) uint32

GetMemberOffset returns the byte offset of a struct member, or 0 if not decorated.

func (*Module) GetTypeComponentCount added in v0.27.0

func (m *Module) GetTypeComponentCount(varID uint32) int

GetTypeComponentCount returns the number of scalar components for the type pointed to by a variable. For vec2 returns 2, vec3 returns 3, vec4 returns 4, scalars return 1. Returns 0 if the variable or type is unknown.

func (*Module) GetWorkgroupSize added in v0.27.0

func (m *Module) GetWorkgroupSize(entryPoint string) [3]uint32

GetWorkgroupSize returns the workgroup size declared via OpExecutionMode LocalSize. Returns (1, 1, 1) if not specified.

func (*Module) PointeeType added in v0.27.0

func (m *Module) PointeeType(ptrTypeID uint32) *TypeInfo

PointeeType dereferences a pointer type, returning the type it points to.

type Pointer added in v0.27.0

type Pointer struct {
	Val Value
}

Pointer wraps a mutable reference to a Value stored in a variable. SPIR-V OpVariable creates a Pointer; OpLoad dereferences it; OpStore writes to it.

type SampledImageValue added in v0.27.0

type SampledImageValue struct {
	Image   Value // BindingKey or *Texture2D (stored as Value)
	Sampler Value // BindingKey or *Sampler (stored as Value)
}

SampledImageValue combines a texture reference and a sampler reference. Created by OpSampledImage, consumed by OpImageSample* opcodes.

type Sampler added in v0.27.0

type Sampler struct {
	MinFilter uint32 // 0 = Nearest, 1 = Linear.
	MagFilter uint32 // 0 = Nearest, 1 = Linear.
	WrapU     uint32 // 0 = Repeat, 1 = ClampToEdge, 2 = MirroredRepeat.
	WrapV     uint32 // 0 = Repeat, 1 = ClampToEdge, 2 = MirroredRepeat.
}

Sampler describes texture sampling parameters.

type ShaderProgram

type ShaderProgram struct {
	// Vertex is the vertex shader function.
	Vertex VertexShaderFunc

	// Fragment is the fragment shader function.
	Fragment FragmentShaderFunc
}

ShaderProgram combines vertex and fragment shaders into a complete program.

func (ShaderProgram) IsValid

func (p ShaderProgram) IsValid() bool

IsValid returns true if the shader program has both vertex and fragment shaders.

type SolidColorUniforms

type SolidColorUniforms struct {
	// MVP is the Model-View-Projection matrix in column-major order.
	MVP [16]float32

	// Color is the RGBA color to render with values in [0, 1].
	Color [4]float32
}

SolidColorUniforms contains uniform data for the solid color shader.

type SubPointer added in v0.27.0

type SubPointer struct {
	Parent  *Pointer // root variable pointer
	Indexes []uint32 // index path from parent to sub-element (literal values, not SSA IDs)
}

SubPointer provides write-through access to a member of a composite value stored in a parent Pointer. When SPIR-V uses OpAccessChain on a function-local variable (e.g. var p: Particle; p.pos), OpStore to the resulting pointer must update the parent composite -- not just a disconnected copy.

Without SubPointer, accessChain creates a new Pointer wrapping a copy of the sub-element, so OpStore modifies the copy but not the original struct. This bug caused compute shaders with struct member updates (p.pos += ...) to silently discard writes.

SubPointer solves this by storing a reference to the parent Pointer and the index path. OpLoad reads the current value through the parent. OpStore writes back through the parent, rebuilding the composite at each level.

type Texture2D added in v0.27.0

type Texture2D struct {
	Width  uint32
	Height uint32
	Data   []byte // RGBA pixel data, row-major, 4 bytes per pixel.
	Format uint32 // Texture format identifier (0 = RGBA8).
}

Texture2D represents a 2D texture for sampling in the SPIR-V interpreter.

type TexturedUniforms

type TexturedUniforms struct {
	// MVP is the Model-View-Projection matrix in column-major order.
	MVP [16]float32

	// TextureData is the RGBA8 texture data.
	TextureData []byte

	// TextureWidth is the width of the texture in pixels.
	TextureWidth int

	// TextureHeight is the height of the texture in pixels.
	TextureHeight int
}

TexturedUniforms contains uniform data for the textured shader.

type TypeInfo added in v0.27.0

type TypeInfo struct {
	Kind       TypeKind
	Width      uint32   // bit width for int/float
	Signed     bool     // for OpTypeInt
	Components uint32   // for OpTypeVector
	ElemType   uint32   // element type ID for vector/array/pointer
	Length     uint32   // for OpTypeArray (number of elements)
	Storage    uint32   // for OpTypePointer (storage class)
	ParamIDs   []uint32 // for OpTypeFunction (parameter type IDs)
	ReturnType uint32   // for OpTypeFunction
	MemberIDs  []uint32 // for OpTypeStruct
}

TypeInfo describes a SPIR-V type.

type TypeKind added in v0.27.0

type TypeKind int

TypeKind classifies SPIR-V types.

const (
	TypeVoid TypeKind = iota
	TypeBool
	TypeInt
	TypeFloat
	TypeVector
	TypeArray
	TypePointer
	TypeFunction
	TypeStruct
	TypeImage
	TypeSampler
	TypeSampledImage
)

type Uint32 added in v0.27.0

type Uint32 = uint32

Type aliases kept for backward compatibility with external code and tests. These are the underlying Go types used for construction only.

type Value added in v0.27.0

type Value struct {
	Tag ValueTag
	F   [4]float32     // float scalars + vectors
	U   [4]uint32      // uint/int scalars, bool, binding key
	Ref unsafe.Pointer // Array, Pointer, SubPointer, BufferPointer, SampledImageValue
}

Value is a tagged union representing a runtime value in the SPIR-V interpreter. Scalars and vectors (up to vec4) are stored inline with zero heap allocation. Composite types (arrays, pointers) use the Ref field.

Size: 40 bytes (1 tag + 3 pad + 16 F + 16 U + 8 Ref = 44, but compiler may align to 48). This is intentionally larger than an interface (16 bytes) because it eliminates the heap allocation that every interface boxing requires.

func ValArray added in v0.27.0

func ValArray(a []Value) Value

ValArray returns an Array Value. The slice is stored on the heap via Ref.

func ValBindingKey added in v0.27.0

func ValBindingKey(bk BindingKey) Value

ValBindingKey returns a BindingKey Value stored inline in U[0..1].

func ValBool added in v0.27.0

func ValBool(b bool) Value

ValBool returns a boolean Value.

func ValBufferPointer added in v0.27.0

func ValBufferPointer(bp *BufferPointer) Value

ValBufferPointer returns a BufferPointer Value.

func ValFloat added in v0.27.0

func ValFloat(f float32) Value

ValFloat returns a float32 scalar Value.

func ValInt added in v0.27.0

func ValInt(i int32) Value

ValInt returns an int32 scalar Value.

func ValNone added in v0.27.0

func ValNone() Value

ValNone returns the zero/nil Value.

func ValPointer added in v0.27.0

func ValPointer(p *Pointer) Value

ValPointer returns a Pointer Value.

func ValSampledImage added in v0.27.0

func ValSampledImage(si *SampledImageValue) Value

ValSampledImage returns a SampledImageValue.

func ValSubPointer added in v0.27.0

func ValSubPointer(sp *SubPointer) Value

ValSubPointer returns a SubPointer Value.

func ValUint added in v0.27.0

func ValUint(u uint32) Value

ValUint returns a uint32 scalar Value.

func ValVec2 added in v0.27.0

func ValVec2(x, y float32) Value

ValVec2 returns a 2-component float vector Value.

func ValVec2From added in v0.27.0

func ValVec2From(v Vec2) Value

ValVec2From returns a Value from a Vec2 array.

func ValVec3 added in v0.27.0

func ValVec3(x, y, z float32) Value

ValVec3 returns a 3-component float vector Value.

func ValVec3From added in v0.27.0

func ValVec3From(v Vec3) Value

ValVec3From returns a Value from a Vec3 array.

func ValVec4 added in v0.27.0

func ValVec4(x, y, z, w float32) Value

ValVec4 returns a 4-component float vector Value.

func ValVec4From added in v0.27.0

func ValVec4From(v Vec4) Value

ValVec4From returns a Value from a Vec4 array.

func (Value) AsArray added in v0.27.0

func (v Value) AsArray() []Value

AsArray extracts a []Value from the Ref field.

func (Value) AsBindingKey added in v0.27.0

func (v Value) AsBindingKey() BindingKey

AsBindingKey extracts a BindingKey from U[0..1].

func (Value) AsBool added in v0.27.0

func (v Value) AsBool() bool

AsBool extracts a bool. Returns false for non-bool tags.

func (Value) AsBufferPointer added in v0.27.0

func (v Value) AsBufferPointer() *BufferPointer

AsBufferPointer extracts a *BufferPointer from the Ref field.

func (Value) AsFloat32 added in v0.27.0

func (v Value) AsFloat32() float32

AsFloat32 extracts a float32. Returns 0 for non-float tags.

func (Value) AsInt32 added in v0.27.0

func (v Value) AsInt32() int32

AsInt32 extracts an int32. Returns 0 for non-int tags.

func (Value) AsPointer added in v0.27.0

func (v Value) AsPointer() *Pointer

AsPointer extracts a *Pointer from the Ref field.

func (Value) AsSampledImage added in v0.27.0

func (v Value) AsSampledImage() *SampledImageValue

AsSampledImage extracts a *SampledImageValue from the Ref field.

func (Value) AsSubPointer added in v0.27.0

func (v Value) AsSubPointer() *SubPointer

AsSubPointer extracts a *SubPointer from the Ref field.

func (Value) AsUint32 added in v0.27.0

func (v Value) AsUint32() uint32

AsUint32 extracts a uint32. Returns 0 for non-uint tags.

func (Value) AsVec2 added in v0.27.0

func (v Value) AsVec2() Vec2

AsVec2 extracts a [2]float32.

func (Value) AsVec3 added in v0.27.0

func (v Value) AsVec3() Vec3

AsVec3 extracts a [3]float32.

func (Value) AsVec4 added in v0.27.0

func (v Value) AsVec4() Vec4

AsVec4 extracts a [4]float32.

func (Value) IsNone added in v0.27.0

func (v Value) IsNone() bool

IsNone returns true if the value is uninitialized/nil.

type ValueTag added in v0.27.0

type ValueTag byte

ValueTag identifies the concrete type stored in a Value.

const (
	TagNone          ValueTag = iota
	TagFloat32                // scalar float32 in F[0]
	TagUint32                 // scalar uint32 in U[0]
	TagInt32                  // scalar int32 (stored as uint32 in U[0])
	TagBool                   // boolean (U[0]: 0=false, 1=true)
	TagVec2                   // [2]float32 in F[0..1]
	TagVec3                   // [3]float32 in F[0..2]
	TagVec4                   // [4]float32 in F[0..3]
	TagArray                  // []Value stored via Ref
	TagPointer                // *Pointer stored via Ref
	TagSubPointer             // *SubPointer stored via Ref
	TagBufferPointer          // *BufferPointer stored via Ref
	TagSampledImage           // *SampledImageValue stored via Ref
	TagBindingKey             // BindingKey stored in U[0..1]
)

type VariableInfo added in v0.27.0

type VariableInfo struct {
	TypeID       uint32 // pointer type ID
	StorageClass uint32
}

VariableInfo describes an OpVariable.

type Vec2 added in v0.27.0

type Vec2 = [2]float32

Type aliases kept for backward compatibility with external code and tests. These are the underlying Go types used for construction only.

type Vec3 added in v0.27.0

type Vec3 = [3]float32

Type aliases kept for backward compatibility with external code and tests. These are the underlying Go types used for construction only.

type Vec4 added in v0.27.0

type Vec4 = [4]float32

Type aliases kept for backward compatibility with external code and tests. These are the underlying Go types used for construction only.

type Vertex

type Vertex struct {
	// Position in object/model space.
	Position [3]float32

	// Attributes are additional per-vertex data (colors, UVs, normals, etc.).
	Attributes []float32
}

Vertex represents input vertex data for processing.

func NewVertex

func NewVertex(x, y, z float32) Vertex

NewVertex creates a vertex with position only.

func NewVertexWithColor

func NewVertexWithColor(x, y, z, r, g, b, a float32) Vertex

NewVertexWithColor creates a vertex with position and RGBA color.

func NewVertexWithColorAndUV

func NewVertexWithColorAndUV(x, y, z, r, g, b, a, u, v float32) Vertex

NewVertexWithColorAndUV creates a vertex with position, RGBA color, and UV coordinates.

func NewVertexWithUV

func NewVertexWithUV(x, y, z, u, v float32) Vertex

NewVertexWithUV creates a vertex with position and UV texture coordinates.

type VertexColorUniforms

type VertexColorUniforms struct {
	// MVP is the Model-View-Projection matrix in column-major order.
	MVP [16]float32
}

VertexColorUniforms contains uniform data for the per-vertex color shader.

type VertexShaderFunc

type VertexShaderFunc func(
	vertexIndex int,
	position [3]float32,
	attributes []float32,
	uniforms any,
) raster.ClipSpaceVertex

VertexShaderFunc transforms a vertex from object space to clip space. It receives vertex data and returns a clip-space vertex with position and attributes.

Parameters:

  • vertexIndex: The index of the vertex being processed.
  • position: The 3D position of the vertex in object/world space.
  • attributes: Additional vertex attributes (colors, UVs, normals, etc.).
  • uniforms: User-defined uniform data (matrices, colors, etc.).

Returns:

  • ClipSpaceVertex: The transformed vertex with clip-space position and attributes to be interpolated across the triangle.

Jump to

Keyboard shortcuts

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