render

package
v0.0.0-...-2fe9ae2 Latest Latest
Warning

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

Go to latest
Published: Mar 18, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Index

Constants

View Source
const MsdfShaderSrc = `` /* 3234-byte string literal not displayed */

MsdfShaderSrc is the MSDF fragment shader.

EXPERIMENTAL — This shader is used when IsMultiChannel() is true. MSDF font generation currently produces inconsistent quality (see msdf.go). The SDF shader (SdfShaderSrc) is recommended for production use.

View Source
const SdfShaderSrc = `` /* 1313-byte string literal not displayed */

Variables

View Source
var (
	// AtlasPageFn resolves an atlas page index to its *ebiten.Image.
	AtlasPageFn func(pageIdx int) *ebiten.Image

	// EnsureMagentaImageFn returns the magenta placeholder image.
	EnsureMagentaImageFn func() *ebiten.Image

	// ShouldCullFn determines whether a node should be culled.
	// Imported from camera/ via root wiring.
	ShouldCullFn func(n *node.Node, viewWorld [6]float64, cullBounds types.Rect) bool

	// EnsureSDFShaderFn lazily compiles and returns the SDF shader.
	EnsureSDFShaderFn func() *ebiten.Shader

	// EnsureMSDFShaderFn lazily compiles and returns the MSDF shader.
	EnsureMSDFShaderFn func() *ebiten.Shader

	// BlendMaskFn returns the blend mode for masking operations.
	BlendMaskFn func() types.BlendMode
)
View Source
var (
	// PageFn resolves an atlas page index to its *ebiten.Image.
	PageFn func(pageIdx int) *ebiten.Image

	// MagentaImageFn returns the magenta placeholder image.
	MagentaImageFn func() *ebiten.Image

	// MagentaPlaceholderPage is the sentinel page index for the magenta placeholder.
	MagentaPlaceholderPage uint16 = 0xFFFF

	// NewSpriteFn creates a new sprite node (wired by root constructors).
	NewSpriteFn func(name string, region types.TextureRegion) *node.Node
)
View Source
var IdentityTransform32 = [6]float32{1, 0, 0, 1, 0, 0}

IdentityTransform32 is the identity affine matrix as float32.

Functions

func Affine32

func Affine32(m [6]float64) [6]float32

Affine32 converts a [6]float64 affine matrix to [6]float32.

func ApplyDrawOpts

func ApplyDrawOpts(op *ebiten.DrawImageOptions, opts RenderTextureDrawOpts, offsetX, offsetY float64)

ApplyDrawOpts configures an ebiten.DrawImageOptions from RenderTextureDrawOpts.

func ApplyFiltersAny

func ApplyFiltersAny(filters []any, src *ebiten.Image, pool *RenderTexturePool) *ebiten.Image

ApplyFiltersAny runs a filter chain on src using []any filters, ping-ponging between two images.

func Clamp01

func Clamp01(v float64) float64

Clamp01 clamps a float64 to [0, 1].

func ColorToRGBA

func ColorToRGBA(c types.Color) colorRGBA

ColorToRGBA converts a types.Color to a color.Color (premultiplied) for image.Fill.

func CommandGeoM

func CommandGeoM(cmd *RenderCommand) ebiten.GeoM

CommandGeoM converts a command's [6]float32 transform into an ebiten.GeoM.

func CommandLessOrEqual

func CommandLessOrEqual(a, b RenderCommand) bool

CommandLessOrEqual returns true if a should sort before or at the same position as b. Using <= for TreeOrder ensures stability.

func DrawFinalScreenFXAA

func DrawFinalScreenFXAA(screen ebiten.FinalScreen, offscreen *ebiten.Image, geoM ebiten.GeoM, cfg FXAAConfig)

DrawFinalScreenFXAA applies the FXAA shader when drawing the final screen.

func EmitNodeCommand

func EmitNodeCommand(p *Pipeline, n *node.Node, transform [6]float64, alpha float64, treeOrder *int)

EmitNodeCommand emits a render command for a single node at the given transform.

func EnsureFXAAShader

func EnsureFXAAShader() *ebiten.Shader

EnsureFXAAShader lazily compiles and returns the FXAA screen shader.

func EnsureMSDFShader

func EnsureMSDFShader() *ebiten.Shader

EnsureMSDFShader lazily compiles the multi-channel SDF shader.

func EnsureSDFShader

func EnsureSDFShader() *ebiten.Shader

EnsureSDFShader lazily compiles and returns the single-channel SDF shader.

func EnsureUniforms

func EnsureUniforms(tb *text.TextBlock, displayScale float64)

EnsureUniforms builds or updates the cached uniform map for the SDF shader.

func InitShaders

func InitShaders()

InitShaders eagerly compiles all built-in render shaders so that any compilation failure panics at startup rather than at an unpredictable frame.

func InvalidateAncestorCache

func InvalidateAncestorCache(n *node.Node)

InvalidateAncestorCache walks up the tree from n to find the nearest CacheAsTree ancestor and marks it dirty (auto mode only).

func InvalidateCacheTree

func InvalidateCacheTree(n *node.Node)

InvalidateCacheTree marks the node's cache as stale.

func InvertAffine32

func InvertAffine32(m [6]float32) [6]float32

InvertAffine32 computes the inverse of a 2D affine matrix in float32.

func MergeSort

func MergeSort(commands []RenderCommand, sortBuf *[]RenderCommand)

MergeSort sorts commands in-place using sortBuf as scratch space. Bottom-up merge sort: zero allocations after the sort buffer reaches high-water mark.

This is the active sort used by Pipeline.Sort(). Benchmarked against RadixSort (2026-03-16) on 10k commands: merge sort matched or beat radix sort because the final scatter of large RenderCommand structs (~300B each) negates the advantage of sorting smaller (key, index) pairs. The O(n) already-sorted fast path also makes merge sort near-free for static scenes.

func MultiplyAffine32

func MultiplyAffine32(p, c [6]float32) [6]float32

MultiplyAffine32 multiplies two 2D affine matrices stored as [6]float32.

func NextPowerOfTwo

func NextPowerOfTwo(n int) int

NextPowerOfTwo returns the smallest power of two >= n (minimum 1).

func NodeDimensions

func NodeDimensions(n *node.Node) (w, h float64)

NodeDimensions returns the width and height used for bounds/culling.

func RadixSort

func RadixSort(commands []RenderCommand, sortBuf *[]RenderCommand, entries, entriesBuf *[]sortEntry)

RadixSort sorts commands using LSD radix sort on packed 64-bit keys. Operates on small (key, index) pairs during sorting, then scatters the full commands once at the end. Zero allocations after buffers reach high-water mark.

Not currently used — see benchmark note above. To switch:

func (p *Pipeline) Sort() {
    RadixSort(p.Commands, &p.SortBuf, &p.SortKeys, &p.SortKeysBuf)
}

func RebuildSortedChildren

func RebuildSortedChildren(n *node.Node)

RebuildSortedChildren rebuilds the ZIndex-sorted traversal order for a node. Uses insertion sort: zero allocations, stable, and optimal for the typical case of few children that are nearly sorted.

func RectUnion

func RectUnion(a, b types.Rect) types.Rect

RectUnion returns the smallest Rect containing both a and b.

func RegisterAnimatedInCache

func RegisterAnimatedInCache(n *node.Node)

RegisterAnimatedInCache walks up to the nearest CacheAsTree ancestor and promotes this node's cachedCmd from static to animated so replay reads the live TextureRegion.

func ResolvePage

func ResolvePage(pageIdx uint16) *ebiten.Image

ResolvePage returns the atlas page image for a page index.

func SetCacheAsTree

func SetCacheAsTree(n *node.Node, enabled bool, mode ...types.CacheTreeMode)

SetCacheAsTree enables or disables subtree command caching on a node.

func SetCacheTreeData

func SetCacheTreeData(n *node.Node, ctd *CacheTreeData)

SetCacheTreeData sets a node's CacheData to a CacheTreeData.

func SubtreeBounds

func SubtreeBounds(n *node.Node) types.Rect

SubtreeBounds computes the bounding rectangle of a node and all its descendants in the node's local coordinate space.

func TransformRect

func TransformRect(t [6]float64, r types.Rect) types.Rect

TransformRect transforms an arbitrary Rect through an affine matrix and returns the axis-aligned bounding box of the result.

func WorldAABB

func WorldAABB(transform [6]float64, w, h float64) types.Rect

WorldAABB computes the axis-aligned bounding box for a rectangle of size (w, h) at the origin, transformed by the given affine matrix.

Types

type BatchKey

type BatchKey struct {
	TargetID uint16
	ShaderID uint16
	Blend    types.BlendMode
	Page     uint16
}

BatchKey groups render commands that can be submitted in a single draw call.

func CommandBatchKey

func CommandBatchKey(cmd *RenderCommand) BatchKey

CommandBatchKey extracts the batch grouping key from a render command.

type BatchMode

type BatchMode uint8

BatchMode controls how the render pipeline submits draw calls.

const (
	// BatchModeCoalesced accumulates vertices and submits one DrawTriangles32 per batch key run.
	BatchModeCoalesced BatchMode = iota
	// BatchModeImmediate submits one DrawImage per sprite (legacy).
	BatchModeImmediate
)

type CacheTreeData

type CacheTreeData struct {
	Mode            types.CacheTreeMode
	Dirty           bool
	Commands        []CachedCmd
	ParentTransform [6]float32
	ParentAlpha     float32
}

CacheTreeData holds subtree command cache state. Allocated on first SetCacheAsTree(true) call. Only a handful of nodes ever use this. Stored on Node.CacheData as an opaque `any`.

func GetCacheTreeData

func GetCacheTreeData(n *node.Node) *CacheTreeData

GetCacheTreeData extracts the CacheTreeData from a node's CacheData field. Returns nil if CacheData is nil or a different type.

type CachedCmd

type CachedCmd struct {
	Cmd          RenderCommand // Transform/Color stored as-is at cache time
	Source       *node.Node    // nil = static, non-nil = animated (read live TextureRegion)
	SourceNodeID uint32        // emitting node's ID, for deferred animated registration lookup
}

CachedCmd is a render command with transform/color stored at cache time. The two-tier source pointer supports animated tiles: nil = static (use cmd.TextureRegion), non-nil = animated (read live TextureRegion from node).

type Color32

type Color32 struct {
	R, G, B, A float32
}

Color32 is a compact RGBA color using float32, for render commands only.

type CommandType

type CommandType uint8

CommandType identifies the kind of render command.

const (
	CommandSprite     CommandType = iota // DrawImage
	CommandMesh                          // DrawTriangles
	CommandParticle                      // particle quads (batches as sprites)
	CommandTilemap                       // DrawTriangles for tilemap layers
	CommandSDF                           // DrawTrianglesShader for SDF text glyphs
	CommandBitmapText                    // DrawTriangles for pixel-perfect bitmap font glyphs
)

type FXAAConfig

type FXAAConfig struct {
	// SubpixQuality controls sub-pixel aliasing removal (0.0 = off, 1.0 = max). Default: 0.75.
	SubpixQuality float32
	// EdgeThreshold is the minimum local contrast required to trigger AA.
	// Lower catches more edges but increases blur. Default: 0.166.
	EdgeThreshold float32
	// EdgeThresholdMin skips AA on pixels below this darkness threshold.
	// Prevents noise in shadowed areas. Default: 0.0312.
	EdgeThresholdMin float32
}

FXAAConfig holds tunable parameters for the FXAA post-process pass.

func DefaultFXAAConfig

func DefaultFXAAConfig() FXAAConfig

DefaultFXAAConfig returns an FXAAConfig with the FXAA 3.11 quality-15 defaults.

type Pipeline

type Pipeline struct {
	Commands               []RenderCommand
	SortBuf                []RenderCommand
	BatchVerts             []ebiten.Vertex
	BatchInds              []uint32
	RtPool                 RenderTexturePool
	RtDeferred             []*ebiten.Image
	OffscreenCmds          []RenderCommand
	CullBounds             types.Rect
	CullActive             bool
	ViewTransform          [6]float64
	BuildingCacheFor       *node.Node
	CommandsDirtyThisFrame bool
	BatchMode              BatchMode
	SortKeys               []sortEntry
	SortKeysBuf            []sortEntry
}

Pipeline owns all render state that was previously on Scene: command buffer, sort buffer, batch vertex/index buffers, RT pool, deferred RT list, offscreen commands, culling, and batch mode.

func (*Pipeline) AppendCommand

func (p *Pipeline) AppendCommand(cmd RenderCommand)

AppendCommand appends a render command. Used by CustomEmit callbacks.

func (*Pipeline) AppendSpriteQuad

func (p *Pipeline) AppendSpriteQuad(cmd *RenderCommand)

AppendSpriteQuad appends 4 vertices and 6 indices for a single atlas sprite.

func (*Pipeline) ReleaseDeferred

func (p *Pipeline) ReleaseDeferred()

ReleaseDeferred releases all deferred render targets back to the pool.

func (*Pipeline) RenderSubtree

func (p *Pipeline) RenderSubtree(n *node.Node, target *ebiten.Image, bounds types.Rect)

func (*Pipeline) Sort

func (p *Pipeline) Sort()

Sort sorts the command buffer using radix sort.

func (*Pipeline) SubmitBatches

func (p *Pipeline) SubmitBatches(target *ebiten.Image)

SubmitBatches iterates sorted commands and submits draw calls to the target.

func (*Pipeline) SubmitBatchesCoalesced

func (p *Pipeline) SubmitBatchesCoalesced(target *ebiten.Image)

func (*Pipeline) Traverse

func (p *Pipeline) Traverse(n *node.Node, treeOrder *int)

Traverse walks the node tree depth-first, emitting render commands for visible, renderable leaf nodes.

type RenderCommand

type RenderCommand struct {
	Type          CommandType
	Transform     [6]float32
	TextureRegion types.TextureRegion
	Color         Color32
	BlendMode     types.BlendMode
	ShaderID      uint16
	TargetID      uint16
	RenderLayer   uint8
	GlobalOrder   int
	TreeOrder     int // assigned during traversal for stable sort

	// Mesh-only fields (slice headers, not copies of vertex data).
	MeshVerts []ebiten.Vertex
	MeshInds  []uint16
	MeshImage *ebiten.Image

	// DirectImage, when non-nil, is drawn directly instead of looking up an
	// atlas page. Used for cached/filtered/masked node output.
	DirectImage *ebiten.Image

	// Emitter references the particle emitter for CommandParticle commands.
	Emitter            *particle.Emitter
	WorldSpaceParticle bool // particles store world positions; Transform is view-only

	// TransientDirectImage is true when DirectImage points to a pooled RT
	// that is released after the frame.
	TransientDirectImage bool

	// EmittingNodeID is set during CacheAsTree builds to track which Node
	// emitted this command.
	EmittingNodeID uint32

	// Tilemap fields (CommandTilemap only — slice headers, not copies).
	TilemapVerts []ebiten.Vertex
	TilemapInds  []uint16
	TilemapImage *ebiten.Image

	// SDF text fields (CommandSDF only — slice headers, not copies).
	SdfVerts     []ebiten.Vertex // local-space glyph quads (from TextBlock cache)
	SdfInds      []uint16        // glyph indices (from TextBlock cache)
	SdfVertCount int             // active vertex count
	SdfIndCount  int             // active index count
	SdfShader    *ebiten.Shader  // SDF or MSDF shader
	SdfAtlasImg  *ebiten.Image   // font's SDF atlas page
	SdfUniforms  map[string]any  // shader uniforms (threshold, smoothing, effects)

	// Bitmap text fields (CommandBitmapText only — slice headers, not copies).
	BmpVerts     []ebiten.Vertex
	BmpInds      []uint16
	BmpVertCount int
	BmpIndCount  int
	BmpImage     *ebiten.Image
}

RenderCommand is a single draw instruction emitted during scene traversal.

func EmitPixelTextCommand

func EmitPixelTextCommand(tb *text.TextBlock, n *node.Node, worldTransform [6]float64, commands []RenderCommand, treeOrder *int) []RenderCommand

EmitPixelTextCommand emits a CommandBitmapText for pixel-perfect bitmap font rendering.

func EmitSDFTextCommand

func EmitSDFTextCommand(tb *text.TextBlock, n *node.Node, worldTransform [6]float64, commands []RenderCommand, treeOrder *int) []RenderCommand

EmitSDFTextCommand emits a CommandSDF carrying local-space glyph quads.

type RenderTexture

type RenderTexture struct {
	Img  *ebiten.Image
	W, H int
}

RenderTexture is a persistent offscreen canvas that can be attached to a sprite node via SetCustomImage. Unlike pooled render targets used internally, a RenderTexture is owned by the caller and is NOT recycled between frames.

func NewRenderTexture

func NewRenderTexture(w, h int) *RenderTexture

NewRenderTexture creates a persistent offscreen canvas of the given size.

func (*RenderTexture) Clear

func (rt *RenderTexture) Clear()

Clear fills the texture with transparent black.

func (*RenderTexture) Dispose

func (rt *RenderTexture) Dispose()

Dispose deallocates the underlying image.

func (*RenderTexture) DrawImage

func (rt *RenderTexture) DrawImage(src *ebiten.Image, op *ebiten.DrawImageOptions)

DrawImage draws src onto this texture using the provided options.

func (*RenderTexture) DrawImageAt

func (rt *RenderTexture) DrawImageAt(src *ebiten.Image, x, y float64, blend types.BlendMode)

DrawImageAt draws src at the given position with the specified blend mode.

func (*RenderTexture) DrawImageColored

func (rt *RenderTexture) DrawImageColored(img *ebiten.Image, opts RenderTextureDrawOpts)

DrawImageColored draws a raw *ebiten.Image with full transform, color, and alpha.

func (*RenderTexture) DrawSprite

func (rt *RenderTexture) DrawSprite(region types.TextureRegion, x, y float64, blend types.BlendMode, pages []*ebiten.Image)

DrawSprite draws a TextureRegion from the atlas onto this texture at (x, y).

func (*RenderTexture) DrawSpriteColored

func (rt *RenderTexture) DrawSpriteColored(region types.TextureRegion, opts RenderTextureDrawOpts, pages []*ebiten.Image)

DrawSpriteColored draws a TextureRegion with full transform, color, and alpha.

func (*RenderTexture) Fill

func (rt *RenderTexture) Fill(c types.Color)

Fill fills the entire texture with the given color.

func (*RenderTexture) Height

func (rt *RenderTexture) Height() int

Height returns the texture height in pixels.

func (*RenderTexture) Image

func (rt *RenderTexture) Image() *ebiten.Image

Image returns the underlying *ebiten.Image for direct manipulation.

func (*RenderTexture) NewSpriteNode

func (rt *RenderTexture) NewSpriteNode(name string) *node.Node

NewSpriteNode creates a NodeTypeSprite with CustomImage pre-set to this texture. The returned node will display the RenderTexture contents.

func (*RenderTexture) Resize

func (rt *RenderTexture) Resize(width, height int)

Resize deallocates the old image and creates a new one at the given dimensions.

func (*RenderTexture) Width

func (rt *RenderTexture) Width() int

Width returns the texture width in pixels.

type RenderTextureDrawOpts

type RenderTextureDrawOpts struct {
	X, Y           float64
	ScaleX, ScaleY float64
	Rotation       float64
	PivotX, PivotY float64
	Color          types.Color
	Alpha          float64
	BlendMode      types.BlendMode
}

RenderTextureDrawOpts controls how an image or sprite is drawn onto a RenderTexture when using the "Colored" draw methods.

type RenderTexturePool

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

RenderTexturePool manages reusable offscreen ebiten.Images keyed by power-of-two dimensions. After warmup, Acquire/Release are zero-alloc.

func (*RenderTexturePool) Acquire

func (p *RenderTexturePool) Acquire(w, h int) *ebiten.Image

Acquire returns a cleared offscreen image with at least (w, h) pixels. Dimensions are rounded up to the next power of two.

func (*RenderTexturePool) Release

func (p *RenderTexturePool) Release(img *ebiten.Image)

Release returns an image to the pool for reuse.

Jump to

Keyboard shortcuts

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