shaderir

package
v0.3.4 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: Apache-2.0 Imports: 10 Imported by: 0 modules, 0 packages

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

Documentation

Overview

Package shaderir offers intermediate representation for shader programs, forked from Ebitengine with package shader (see its documentation).

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsValidSwizzling

func IsValidSwizzling(s string) bool

func PutLanes

func PutLanes(buf []byte, offsets []int, types []BasicType, values []float64, boolSize int)

PutLanes writes values into buf, a uniform buffer: each at its offset in bytes (a backend's UniformLanes) as a little-endian 32-bit number of its type (LaneTypes), an int, uint or bool from the value's integer part, and a bool in boolSize bytes (1 in Metal, 4 elsewhere).

func ResolveUntypedConstsForBinaryOp

func ResolveUntypedConstsForBinaryOp(op Op, lhs, rhs constant.Value, lhst, rhst Type) (newLhs, newRhs constant.Value, ok bool)

Types

type BasicType

type BasicType int
const (
	None BasicType = iota
	Bool
	Int
	Float
	Vec2
	Vec3
	Vec4
	IVec2
	IVec3
	IVec4
	Mat2
	Mat3
	Mat4
	Texture
	Array
	Struct

	// Added by MyGo, after Ebitengine's types.
	Uint
	UVec2
	UVec3
	UVec4
	// Added by NSGo for 3D GPU pipelines (docs/architecture/gpu.md).
	Mat2x3
	Mat2x4
	Mat3x2
	Mat3x4
	Mat4x2
	Mat4x3
	Texture2D
	TextureCube
	Texture2DArray
	TextureDepth2D
	TextureMultisampled2D
	TextureStorage2D
	Sampler
	SamplerComparison
)

func MatrixOf

func MatrixOf(cols, rows int) BasicType

MatrixOf returns the BasicType of a cols x rows float matrix.

func VectorOf

func VectorOf(scalar BasicType, n int) BasicType

VectorOf returns the vector of n components of type scalar, or scalar itself for n 1.

type Binding

type Binding struct {
	Group         uint32
	Binding       uint32
	Name          string
	Kind          BindingKind
	Type          Type
	StorageFormat StorageTextureFormat
	StorageAccess StorageAccess
}

Binding describes a resource declared with @group(G) @binding(B).

type BindingKind

type BindingKind uint8

BindingKind classifies an explicit @group(G) @binding(B) resource binding.

const (
	BindingUniformBuffer BindingKind = iota
	BindingStorageBufferRead
	BindingTexture
	BindingSampler
	BindingStorageBufferReadWrite
	BindingStorageTexture
)

type BindingTypeEnv

type BindingTypeEnv interface {
	BindingType(index int) Type
}

BindingTypeEnv is an optional extension of TypeEnv for programs with explicit @group/@binding resources.

type Block

type Block struct {
	LocalVars           []Type
	LocalVarIndexOffset int
	Stmts               []Stmt
}

type BuiltinFunc

type BuiltinFunc string
const (
	Len         BuiltinFunc = "len"
	Cap         BuiltinFunc = "cap"
	BoolF       BuiltinFunc = "bool"
	IntF        BuiltinFunc = "int"
	FloatF      BuiltinFunc = "float"
	Vec2F       BuiltinFunc = "vec2"
	Vec3F       BuiltinFunc = "vec3"
	Vec4F       BuiltinFunc = "vec4"
	IVec2F      BuiltinFunc = "ivec2"
	IVec3F      BuiltinFunc = "ivec3"
	IVec4F      BuiltinFunc = "ivec4"
	UintF       BuiltinFunc = "uint"
	UVec2F      BuiltinFunc = "uvec2"
	UVec3F      BuiltinFunc = "uvec3"
	UVec4F      BuiltinFunc = "uvec4"
	Mat2F       BuiltinFunc = "mat2"
	Mat3F       BuiltinFunc = "mat3"
	Mat4F       BuiltinFunc = "mat4"
	Radians     BuiltinFunc = "radians" // This function is not used yet (#2253)
	Degrees     BuiltinFunc = "degrees" // This function is not used yet (#2253)
	Sin         BuiltinFunc = "sin"
	Cos         BuiltinFunc = "cos"
	Tan         BuiltinFunc = "tan"
	Asin        BuiltinFunc = "asin"
	Acos        BuiltinFunc = "acos"
	Atan        BuiltinFunc = "atan"
	Atan2       BuiltinFunc = "atan2"
	Pow         BuiltinFunc = "pow"
	Exp         BuiltinFunc = "exp"
	Log         BuiltinFunc = "log"
	Exp2        BuiltinFunc = "exp2"
	Log2        BuiltinFunc = "log2"
	Sqrt        BuiltinFunc = "sqrt"
	Inversesqrt BuiltinFunc = "inversesqrt"
	Abs         BuiltinFunc = "abs"
	Sign        BuiltinFunc = "sign"
	Floor       BuiltinFunc = "floor"
	Ceil        BuiltinFunc = "ceil"
	Fract       BuiltinFunc = "fract"
	Mod         BuiltinFunc = "mod"
	Min         BuiltinFunc = "min"
	Max         BuiltinFunc = "max"
	Clamp       BuiltinFunc = "clamp"
	Mix         BuiltinFunc = "mix"
	Step        BuiltinFunc = "step"
	Smoothstep  BuiltinFunc = "smoothstep"
	Length      BuiltinFunc = "length"
	Distance    BuiltinFunc = "distance"
	Dot         BuiltinFunc = "dot"
	Cross       BuiltinFunc = "cross"
	Normalize   BuiltinFunc = "normalize"
	Faceforward BuiltinFunc = "faceforward"
	Reflect     BuiltinFunc = "reflect"
	Refract     BuiltinFunc = "refract"
	Transpose   BuiltinFunc = "transpose"
	Dfdx        BuiltinFunc = "dfdx"
	Dfdy        BuiltinFunc = "dfdy"
	Fwidth      BuiltinFunc = "fwidth"
	DiscardF    BuiltinFunc = "discard"
	TexelAt     BuiltinFunc = "__texelAt"
	FrontFacing BuiltinFunc = "frontfacing"

	// Added by NSGo for WGSL (package shader/wgsl), which Kage does not
	// name: GLSL's names, which the writers map to their languages'.
	Trunc           BuiltinFunc = "trunc"
	RoundEven       BuiltinFunc = "roundEven"
	Sinh            BuiltinFunc = "sinh"
	Cosh            BuiltinFunc = "cosh"
	Tanh            BuiltinFunc = "tanh"
	FloatBitsToInt  BuiltinFunc = "floatBitsToInt"
	FloatBitsToUint BuiltinFunc = "floatBitsToUint"
	IntBitsToFloat  BuiltinFunc = "intBitsToFloat"
	UintBitsToFloat BuiltinFunc = "uintBitsToFloat"
	// Added by NSGo for 3D GPU pipelines (docs/architecture/gpu.md).
	TextureSample             BuiltinFunc = "textureSample"
	TextureSampleLevel        BuiltinFunc = "textureSampleLevel"
	TextureSampleBias         BuiltinFunc = "textureSampleBias"
	TextureSampleGrad         BuiltinFunc = "textureSampleGrad"
	TextureSampleCompare      BuiltinFunc = "textureSampleCompare"
	TextureSampleCompareLevel BuiltinFunc = "textureSampleCompareLevel"
	TextureLoad               BuiltinFunc = "textureLoad"
	TextureDimensions         BuiltinFunc = "textureDimensions"
	TextureStore              BuiltinFunc = "textureStore"
	ArrayLength               BuiltinFunc = "arrayLength"
	WorkgroupBarrier          BuiltinFunc = "workgroupBarrier"
	StorageBarrier            BuiltinFunc = "storageBarrier"

	// Added by NSGo for WGSL non-square matrices and determinant.
	Mat2x3F     BuiltinFunc = "mat2x3"
	Mat2x4F     BuiltinFunc = "mat2x4"
	Mat3x2F     BuiltinFunc = "mat3x2"
	Mat3x4F     BuiltinFunc = "mat3x4"
	Mat4x2F     BuiltinFunc = "mat4x2"
	Mat4x3F     BuiltinFunc = "mat4x3"
	Determinant BuiltinFunc = "determinant"
)

func ParseBuiltinFunc

func ParseBuiltinFunc(str string) (BuiltinFunc, bool)

type ComputeFunc

type ComputeFunc struct {
	WorkgroupSize [3]uint32
	Block         *Block
}

ComputeFunc holds a @compute entry point with its @workgroup_size(X, Y, Z) and body block.

type Expr

type Expr struct {
	Type        ExprType
	Exprs       []Expr
	Const       constant.Value
	BuiltinFunc BuiltinFunc
	// Swizzling is spelled in the xyzw set regardless of [Expr.SwizzlingSet].
	Swizzling    string
	SwizzlingSet SwizzlingSet
	Index        int
	Op           Op

	// Unsigned marks an expression of type uint or uvecN, as the compiler
	// infers it: a constant of it is written as one (1u), which GLSL ES
	// needs, as it converts no int to uint.
	Unsigned bool

	// Untyped marks an integer expression that is not a constant but takes
	// the type of its context, as in Go: a shift of an untyped constant by
	// a count that is not one, and operations of such shifts with untyped
	// constants. Its type is int where the context gives none.
	Untyped bool

	// StructType carries the struct type for a StructConstruct expression.
	StructType *Type
}

func (Expr) SourceSwizzling

func (e Expr) SourceSwizzling() string

SourceSwizzling returns the swizzle of a SwizzlingExpr spelled in Expr.SwizzlingSet.

type ExprType

type ExprType int
const (
	Blank ExprType = iota
	NumberExpr
	UniformVariable
	TextureVariable
	LocalVariable
	StructMember
	BuiltinFuncExpr
	SwizzlingExpr
	FunctionExpr
	Unary
	Binary
	Selection
	Call
	FieldSelector
	Index
	// Added by NSGo for 3D GPU pipelines (docs/architecture/gpu.md).
	BindingVariable
	BuiltinInput
	StructConstruct
	PrivateVariable
)

type FragmentFunc

type FragmentFunc struct {
	Block *Block
}

FragmentFunc takes pseudo params, and the number is len(varyings) + 1. If index == 0, the param represents the coordinate of the fragment (gl_FragCoord in GLSL). If 0 < index <= len(varyings), the param represents (index-1)th varying variable.

type Func

type Func struct {
	Index     int
	InParams  []Type
	OutParams []Type
	Return    Type
	Block     *Block
}

type Interpolation

type Interpolation uint8

Interpolation specifies how a varying is interpolated across a primitive.

const (
	InterpPerspective Interpolation = iota
	InterpFlat
	InterpLinear
)

func (Interpolation) String

func (i Interpolation) String() string

type Op

type Op int
const (
	Add Op = iota
	Sub
	NotOp
	ComplementOp
	ComponentWiseMul
	MatrixMul
	Div
	ModOp
	LeftShift
	RightShift
	LessThanOp
	LessThanEqualOp
	GreaterThanOp
	GreaterThanEqualOp
	EqualOp
	NotEqualOp
	VectorEqualOp
	VectorNotEqualOp
	And
	AndNot
	Xor
	Or
	AndAnd
	OrOr
)

func OpFromToken

func OpFromToken(t token.Token, lhs, rhs Type) (Op, bool)

type Program

type Program struct {
	UniformNames []string
	Uniforms     []Type
	Privates     []Type
	TextureCount int
	Attributes   []Type
	Varyings     []Type
	Funcs        []Func
	VertexFunc   VertexFunc
	FragmentFunc FragmentFunc
	ComputeFunc  ComputeFunc

	// GPU pipeline metadata (docs/architecture/gpu.md). Left empty for legacy
	// fragment-only shaders so existing FragmentLibrary paths stay unchanged.
	AttributeMeta      []StageIO
	VaryingMeta        []StageIO
	FragmentOutputs    []Type
	FragmentOutputMeta []StageIO
	Bindings           []Binding
	VertexEntry        string
	FragmentEntry      string
	ComputeEntry       string

	SourceID SourceID

	// FragmentSource is the Kage source the program was compiled from, or nil if it was not built from
	// Kage source.
	FragmentSource []byte
	// contains filtered or unexported fields
}

func (*Program) AssignedAttributes

func (p *Program) AssignedAttributes() []bool

AssignedAttributes reports, for each attribute, whether the vertex entry point assigns to the whole attribute or a part of it.

func (*Program) FilterUniformVariables

func (p *Program) FilterUniformVariables(uniforms []uint32)

FilterUniformVariables replaces uniform variables with 0 when they are not used. By minimizing uniform variables, more commands can be merged in the graphicscommand package.

func (*Program) FragmentLibrary

func (p *Program) FragmentLibrary() (lib *Program, entry *Func, funcs []*Func)

FragmentLibrary returns the program as a library for a renderer that draws with a vertex stage of its own, as MyGo's do: a program without entry points, whose fragment entry point is the function entry, taking the fragment's position (vec4) and the varyings, and the functions entry reaches, entry last. Backends emit it as a function of the renderer's fragment shader (Fragment in packages glsl, hlsl and msl).

func (*Program) IsPipeline

func (p *Program) IsPipeline() bool

IsPipeline reports whether p uses explicit GPU pipeline stages or bindings rather than the legacy fragment-only UI shader convention.

func (*Program) LaneTypes

func (p *Program) LaneTypes() []BasicType

LaneTypes returns the scalar type of each lane of p's uniforms, in the order of the backends' UniformLanes: a vector's components, a matrix's columns and an array's elements in turn, Type.DwordCount for each.

func (*Program) LocalVariableType

func (p *Program) LocalVariableType(topBlock, block *Block, idx int) Type

func (*Program) ReachableFuncsFromBlock

func (p *Program) ReachableFuncsFromBlock(block *Block) []*Func

type SourceID

type SourceID [16]byte

func CalcSourceID

func CalcSourceID(source []byte) SourceID

func ParseSourceID

func ParseSourceID(str string) (SourceID, error)

ParseSourceID parses a base32 string returned by SourceID.String back into a SourceID.

func (SourceID) String

func (s SourceID) String() string

type StageBuiltin

type StageBuiltin uint8

StageBuiltin identifies a shader stage built-in input or output.

const (
	BuiltinNone StageBuiltin = iota
	BuiltinPosition
	BuiltinVertexIndex
	BuiltinInstanceIndex
	BuiltinFrontFacing
	BuiltinFragDepth
	BuiltinGlobalInvocationID
	BuiltinLocalInvocationID
	BuiltinWorkgroupID
	BuiltinNumWorkgroups
	BuiltinLocalInvocationIndex
)

func (StageBuiltin) String

func (b StageBuiltin) String() string

type StageIO

type StageIO struct {
	Name          string
	Location      uint32
	Builtin       StageBuiltin
	Interpolation Interpolation
}

StageIO carries optional location, built-in, name, and interpolation metadata for a vertex attribute or inter-stage varying.

type Stmt

type Stmt struct {
	Type        StmtType
	Exprs       []Expr
	Blocks      []*Block
	ForVarType  Type
	ForVarIndex int
	ForInit     constant.Value
	ForEnd      constant.Value
	ForOp       Op
	ForDelta    constant.Value
	InitIndex   int
}

Stmt is a statement. A For loop's counter starts from ForInit and runs while it compares with ForEnd as ForOp says, ForDelta at a time; where the compiler made it, Exprs holds the start and the end as expressions, which need not be constants (MyGo's), and ForInit and ForEnd are nil for those that are not.

type StmtType

type StmtType int
const (
	ExprStmt StmtType = iota
	BlockStmt
	Assign
	Init
	If
	For
	Continue
	Break
	Return
	Discard
)

type StorageAccess

type StorageAccess uint8

StorageAccess identifies the access mode of a storage buffer or storage texture.

const (
	StorageAccessRead StorageAccess = iota
	StorageAccessWrite
	StorageAccessReadWrite
)

func (StorageAccess) WGSLName

func (a StorageAccess) WGSLName() string

type StorageTextureFormat

type StorageTextureFormat uint8

StorageTextureFormat identifies the texel format of a storage texture binding.

const (
	StorageFormatUndefined StorageTextureFormat = iota
	StorageFormatRGBA8Unorm
	StorageFormatRGBA16Float
	StorageFormatRGBA32Float
	StorageFormatR32Float
	StorageFormatR32Uint
	StorageFormatR32Sint
)

func (StorageTextureFormat) GLSLName

func (f StorageTextureFormat) GLSLName() string

func (StorageTextureFormat) WGSLName

func (f StorageTextureFormat) WGSLName() string

type SwizzlingSet

type SwizzlingSet int

SwizzlingSet is the naming set of vector components a swizzle is written in.

const (
	SwizzlingSetXYZW SwizzlingSet = iota
	SwizzlingSetRGBA
	SwizzlingSetSTPQ
)

type Type

type Type struct {
	Main       BasicType
	Sub        []Type
	Length     int
	FieldNames []string
}

func TypeFromBinaryOp

func TypeFromBinaryOp(op Op, lhst, rhst Type, lhsConst, rhsConst constant.Value) (Type, bool)

func TypeOf

func TypeOf(e *Expr, env TypeEnv) Type

TypeOf returns the type of e, an expression the compiler checked. A constant has the type of its kind, bool, float or int, or uint when it is Unsigned; a call of a function with output parameters, which only statements make, has none.

func (Type) AlignBytes

func (t Type) AlignBytes() int

AlignBytes returns the WGSL/std140 uniform alignment of t in bytes.

func (Type) DwordCount

func (t Type) DwordCount() int

func (Type) Equal

func (t Type) Equal(rhs *Type) bool

func (Type) IsFloatVector

func (t Type) IsFloatVector() bool

func (Type) IsIntVector

func (t Type) IsIntVector() bool

func (Type) IsInteger

func (t Type) IsInteger() bool

IsInteger reports whether t is int, uint, or a vector of either.

func (Type) IsIntegerVector

func (t Type) IsIntegerVector() bool

IsIntegerVector reports whether t is a vector of int or uint.

func (Type) IsMatrix

func (t Type) IsMatrix() bool

func (Type) IsSampler

func (t Type) IsSampler() bool

func (Type) IsTexture

func (t Type) IsTexture() bool

func (Type) IsUintVector

func (t Type) IsUintVector() bool

IsUintVector reports whether t is uvec2, uvec3 or uvec4.

func (Type) MatrixCols

func (t Type) MatrixCols() int

func (Type) MatrixRows

func (t Type) MatrixRows() int

func (Type) MatrixSize

func (t Type) MatrixSize() int

func (Type) Scalar

func (t Type) Scalar() BasicType

Scalar returns the type of t's components: float for a float vector or a matrix, int or uint for an integer vector, and t's own for a scalar.

func (Type) SizeBytes

func (t Type) SizeBytes() int

SizeBytes returns the WGSL/std140 byte size of t.

func (Type) StorageAlignBytes

func (t Type) StorageAlignBytes() int

StorageAlignBytes returns the WGSL storage / GLSL std430 alignment of t in bytes.

func (Type) StorageSizeBytes

func (t Type) StorageSizeBytes() int

StorageSizeBytes returns the WGSL storage / GLSL std430 byte size of t. For runtime-sized arrays (Length == 0) it returns 0.

func (Type) StorageStride

func (t Type) StorageStride() int

StorageStride returns the WGSL storage / GLSL std430 element stride in bytes for an element type inside a storage buffer array. Unlike std140 uniform arrays, storage array elements are aligned to their own alignment rather than rounded up to 16 bytes.

func (Type) StorageStructFieldOffset

func (t Type) StorageStructFieldOffset(idx int) int

StorageStructFieldOffset returns the std430 / WGSL storage byte offset of field idx in a Struct type.

func (Type) String

func (t Type) String() string

func (Type) StructFieldOffset

func (t Type) StructFieldOffset(idx int) int

StructFieldOffset returns the byte offset of field idx in a Struct type.

func (Type) VectorElementCount

func (t Type) VectorElementCount() int

type TypeEnv

type TypeEnv interface {
	LocalType(index int) Type
	UniformType(index int) Type
	PrivateType(index int) Type
	FuncReturn(index int) Type
}

TypeEnv tells the types of what expressions refer to: local variables, by their index in their function, uniform variables, and the results of functions.

type VertexFunc

type VertexFunc struct {
	Block *Block
}

VertexFunc takes pseudo params, and the number is len(attributes) + len(varyings) + 1. If 0 <= index < len(attributes), the params are in-params and represent attribute variables. If index == len(attributes), the param is an out-param and represents the position in vec4 (gl_Position in GLSL) If len(attributes) + 1 <= index < len(attributes) + len(varyings) + 1, the params are out-params and represent varying variables.

Directories

Path Synopsis
Package wgsl writes validated WGSL source from a shaderir.Program for the WebGPU backend (docs/architecture/gpu.md).
Package wgsl writes validated WGSL source from a shaderir.Program for the WebGPU backend (docs/architecture/gpu.md).

Jump to

Keyboard shortcuts

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