render

package
v0.0.0-...-94fff03 Latest Latest
Warning

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

Go to latest
Published: Dec 5, 2026 License: MIT Imports: 26 Imported by: 1 module, 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 render draws a queue of plain draw items with Ebiten. It does not import ecs: extract systems (package extract) fill the Queue during Update and the Renderer reads it in Draw, so Draw never touches the World.

The package also holds the Ebiten asset types (Texture, Sprite, Atlas, FontSource, Font, Shader) and their loaders for package asset: RegisterLoaders registers them on an asset.Server. Loaders create every Ebiten object in Finish on the game goroutine; Decode is CPU work only. Items hold handles to these assets and the Renderer resolves them through Stores in Draw, so a missing, loading or failed asset draws its placeholder instead of failing.

Panics raised by this package are programmer errors and start with "render: ".

Index

Constants

View Source
const (
	// AssetKindSprite is a [Sprite]: a whole image or an atlas frame.
	AssetKindSprite = "sprite"
	// AssetKindFont is a [Font] ("fonts/ui.ttf#16").
	AssetKindFont = "font"
	// AssetKindShader is a [Shader] (a *.kage file).
	AssetKindShader = "shader"
)

Asset kinds of this package: the names a component field carries in its +game:asset:kind=... marker.

View Source
const ShaderUniformParams = "Params"

ShaderUniformParams is the name of the uniform that carries an item's Params. Declare it as

var Params vec4

to read Item.Params (gfx.Sprite.Params). A shader that does not declare it gets nothing; Ebiten ignores uniforms a shader does not declare.

View Source
const ShaderUniformTime = "Time"

ShaderUniformTime is the name of the uniform that carries the time of the frame in seconds, as set with Renderer.SetTime. Declare it as

var Time float

Every shader the Renderer runs (sprites, layer groups, post passes and the final pass) gets the same value during one frame.

Variables

This section is empty.

Functions

func HoldAtlas

func HoldAtlas(sc *asset.Scope, h AtlasHandle)

HoldAtlas adds sc as an owner of h, like asset.Hold.

func HoldFont

func HoldFont(sc *asset.Scope, h gfx.FontHandle)

HoldFont adds sc as an owner of h, like asset.Hold.

func HoldShader

func HoldShader(sc *asset.Scope, h gfx.ShaderHandle)

HoldShader adds sc as an owner of h, like asset.Hold.

func HoldSprite

func HoldSprite(sc *asset.Scope, h gfx.SpriteHandle)

HoldSprite adds sc as an owner of h, like asset.Hold.

func LoadFont

func LoadFont(sc *asset.Scope, key string) gfx.FontHandle

LoadFont returns the handle for a font key ("fonts/ui.ttf#16") and adds a hold for sc. It never blocks and panics like asset.Load.

func LoadFontSync

func LoadFontSync(sc *asset.Scope, key string) (gfx.FontHandle, error)

LoadFontSync is LoadFont followed by loading until the font is ready or failed, like asset.LoadSync. It blocks.

func LoadShader

func LoadShader(sc *asset.Scope, key string) gfx.ShaderHandle

LoadShader returns the handle for a shader key ("fx/flash.kage") and adds a hold for sc. It never blocks and panics like asset.Load.

func LoadShaderSync

func LoadShaderSync(sc *asset.Scope, key string) (gfx.ShaderHandle, error)

LoadShaderSync is LoadShader followed by loading until the shader is ready or failed, like asset.LoadSync. It blocks.

func LoadSprite

func LoadSprite(sc *asset.Scope, key string) gfx.SpriteHandle

LoadSprite returns the handle for a sprite key ("ui/cursor.png" or "chars/hero.atlas.json#idle_0") and adds a hold for sc. It never blocks and panics like asset.Load.

func LoadSpriteSync

func LoadSpriteSync(sc *asset.Scope, key string) (gfx.SpriteHandle, error)

LoadSpriteSync is LoadSprite followed by loading until the sprite is ready or failed, like asset.LoadSync. It blocks: use it for boot screens, tests and tools.

func RegisterLoaders

func RegisterLoaders(srv *asset.Server, opts LoaderOptions)

RegisterLoaders registers every render asset type and its loader on srv: Texture, Sprite (whole images and atlas frames), Atlas, FontSource and Font and Shader. It creates the placeholder images, so it must run on the game goroutine, and it panics like asset.Register if a type is already registered.

Types

type Atlas

type Atlas struct {
	// Texture is the page the frames are cut from.
	Texture TextureID
	// Sprites maps frame name to sprite. Read it at load or spawn time, not
	// per frame.
	Sprites map[string]gfx.SpriteHandle
	// Order lists the sprites in file order, for index-based frame access.
	Order []gfx.SpriteHandle
}

Atlas is a texture cut into named sprites. Load it with LoadAtlas; its frames are also loadable on their own with LoadSprite and a "#name" key ("chars/hero.atlas.json#idle_0"), which loads the atlas too.

Frames are children of the atlas: they are unloaded with it, and a held frame keeps the atlas (and so its texture) alive.

Formats, chosen by file name:

*.sheet.json  grid sheet: {"image", "frameW", "frameH", "margin", "spacing"};
              optional "pivot": {"x", "y"}; frames are named "0", "1", ...
              left to right, top to bottom
*.tsj         single-image Tiled tileset: cut by tilewidth/tileheight,
              margin, spacing and columns into tilecount frames named by
              local tile ID ("0", "1", ...), see atlas-tiled.go
*.json        TexturePacker JSON (hash or array), see atlas-texturepacker.go

"image" is a path relative to the JSON file's directory.

type AtlasHandle

type AtlasHandle struct{ asset.Ref }

AtlasHandle refers to an Atlas. It is 8 bytes, comparable and pointer-free; the zero value means "none". No component holds one (sprites hold the frames' gfx.SpriteHandle), so it lives here rather than in gfx.

func LoadAtlas

func LoadAtlas(sc *asset.Scope, key string) AtlasHandle

LoadAtlas returns the handle for an atlas key ("chars/hero.sheet.json") and adds a hold for sc. It never blocks and panics like asset.Load.

func LoadAtlasSync

func LoadAtlasSync(sc *asset.Scope, key string) (AtlasHandle, error)

LoadAtlasSync is LoadAtlas followed by loading until the atlas is ready or failed, like asset.LoadSync. It blocks.

type AtlasStore

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

AtlasStore resolves AtlasHandle values to atlases. Get one with AtlasStoreOf. It is a small value; copy it freely.

func AtlasStoreOf

func AtlasStoreOf(srv *asset.Server) AtlasStore

AtlasStoreOf returns the atlas store of srv. It panics like asset.StoreOf if RegisterLoaders has not run on srv.

func (AtlasStore) Err

func (s AtlasStore) Err(h AtlasHandle) error

Err returns why the atlas failed to load, or nil.

func (AtlasStore) Generic

func (s AtlasStore) Generic() *asset.Store[Atlas]

Generic returns the underlying generic store, for loaders and tools that work with asset.Handle[Atlas].

func (AtlasStore) Get

func (s AtlasStore) Get(h AtlasHandle) *Atlas

Get returns the atlas, or the placeholder (an empty atlas); see asset.Store.Get. It does not allocate.

func (AtlasStore) Key

func (s AtlasStore) Key(h AtlasHandle) asset.Key

Key returns the key h was loaded from, or the zero Key for a zero or stale handle.

func (AtlasStore) Lookup

func (s AtlasStore) Lookup(h AtlasHandle) (*Atlas, asset.State)

Lookup is Get plus the load state; see asset.Store.Lookup.

func (AtlasStore) Ready

func (s AtlasStore) Ready(h AtlasHandle) bool

Ready reports whether h refers to a loaded atlas.

type Blend

type Blend uint8

Blend selects how an Item is composited onto what is below it.

const (
	BlendNormal Blend = iota
	BlendAdditive
	// BlendMultiply multiplies what is below by the source color: white
	// keeps it, black darkens it to black. Composite a light map group with
	// it.
	BlendMultiply
	// BlendScreen brightens like BlendAdditive but never exceeds white
	// (src + dst*(1-src)): soft glows, light shafts, flashes.
	BlendScreen
	// BlendSubtract subtracts the source color from what is below
	// (dst - src, alpha unchanged): darkening tints, negative light.
	BlendSubtract
	// BlendLighten keeps the brighter of source and destination per channel
	// (max): overlapping glows that do not add up.
	BlendLighten
	// BlendErase removes what is below by the source's alpha
	// (dst*(1-srcAlpha)). Use it for items inside a layer group, where it
	// cuts holes (fog of war, flashlight masks); on the screen it erases to
	// the window background.
	BlendErase
)

Blend modes.

type Bloom

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

Bloom is the handle PostChain.AddBloom returns, to retune or switch off the effect it added.

func (Bloom) Set

func (b Bloom) Set(p *PostChain, opts BloomOptions)

Set changes the options of the bloom; zero fields take their defaults.

func (Bloom) SetOff

func (b Bloom) SetOff(p *PostChain, off bool)

SetOff switches all passes of the bloom off or on.

type BloomOptions

type BloomOptions struct {
	// Threshold is the brightness (the largest of red, green and blue, 0..1)
	// above which a pixel glows; only the part above it does. Default 0.7.
	Threshold float32
	// Strength scales the glow that is added to the frame. Default 1.
	Strength float32
	// Radius is the distance between the taps of the blur, in pixels of the
	// quarter-size image: 1 blurs over about 8 frame pixels each way. Default
	// 1.
	Radius float32
	// Src is the image whose bright parts glow. The zero value,
	// [TargetChain], is the chain so far: the whole frame. [TargetGroup]
	// makes only the layers of one layer group glow (neon signs, magic,
	// lasers) while equally bright sprites elsewhere do not; the glow is
	// still added to the chain. Any target a pass may read works.
	Src TargetID
}

BloomOptions tunes PostChain.AddBloom. A zero field takes its default, so the zero value is a usable bloom.

type Camera

type Camera struct {
	// Pos is the world position at the viewport center for the current
	// tick.
	Pos gfx.Vec2
	// Prev is the view (position, zoom, rotation) at the previous tick,
	// which Draw blends to the current one (see At). The engine records it
	// at the start of every tick (Snapshot). The zero Prev means "no
	// previous view": frames show the current view, as after Jump.
	Prev CameraPose
	// Zoom is the scale from world units to pixels. Zero means 1.
	Zoom float32
	// Rotation rotates the view, in radians, clockwise on screen.
	Rotation float32
	// Viewport is the screen region the camera draws into. The zero
	// rectangle means the whole screen.
	Viewport image.Rectangle
	// PixelSnap rounds the camera position so that the world sits on whole
	// logical pixels: viewport center - Pos*Zoom becomes an integer, which
	// moves the view by at most half a pixel per axis. The Renderer rounds
	// once per frame, after blending the previous view, and WorldToScreen,
	// ScreenToWorld and WorldBounds round the same way, so picking and
	// culling match the drawn pixels.
	//
	// Use it for pixel art. Without it, a camera at a sub-pixel position
	// under a non-integer Zoom changes, from frame to frame, which texels of
	// a sprite are drawn one pixel wide and which two, and the art shimmers
	// while the camera moves. It is ignored while Rotation is not 0.
	PixelSnap bool
}

Camera is a plain value: a CameraSystem writes it during Update and the Renderer reads a copy in Draw. Pos is the world point shown at the center of the viewport.

All methods take the logical screen size in pixels (the size passed to Ebiten's Layout), because the camera itself does not know it.

func (Camera) At

func (c Camera) At(alpha float32) Camera

At returns a copy whose view is blended from Prev to the current one by alpha in [0,1], for drawing between ticks: position and zoom linearly, rotation along the shorter arc. The copy has no Prev.

func (*Camera) DrawBounds

func (c *Camera) DrawBounds(screen image.Point) gfx.Rect

DrawBounds returns the world rectangle that frames drawn during the current tick can show, for culling in extract systems: the union of WorldBounds at the previous view and at the current one. The Renderer blends the view between the two, so culling against the current view alone could drop a sliver at the trailing screen edge while the camera moves or zooms. PixelSnap needs no extra margin: rounding is monotonic, so the rounded blended view lies between the rounded end views, which WorldBounds already returns. A blended rotation can show slightly more than both end views; the bounds of a rotated view are already larger than the view, which covers it for the small turns of one tick.

func (*Camera) Jump

func (c *Camera) Jump()

Jump clears Prev, so the frames of the rest of the tick show the current view instead of sweeping from the old one: for cuts, snaps and editor camera moves.

func (*Camera) PrevPose

func (c *Camera) PrevPose() CameraPose

PrevPose returns the view at the start of the tick: Prev when it is set, else the current view. The result has Set true.

func (*Camera) ScreenToWorld

func (c *Camera) ScreenToWorld(p gfx.Vec2, screen image.Point) gfx.Vec2

ScreenToWorld converts logical screen pixels to a world position, for mouse picking and aiming. It is the inverse of WorldToScreen, PixelSnap included.

func (*Camera) Snapshot

func (c *Camera) Snapshot()

Snapshot records the current view in Prev. game.Engine calls it at the start of every tick; a schedule without the engine calls it in its first stage, before anything moves the camera.

func (*Camera) ViewportRect

func (c *Camera) ViewportRect(screen image.Point) image.Rectangle

ViewportRect returns the pixel region the camera draws into, given the screen size.

func (*Camera) WorldBounds

func (c *Camera) WorldBounds(screen image.Point) gfx.Rect

WorldBounds returns the axis-aligned world rectangle that contains everything the camera can see, for culling. With a rotation it is larger than the view (it bounds the rotated rectangle). With PixelSnap it is the rounded view's rectangle.

func (*Camera) WorldToScreen

func (c *Camera) WorldToScreen(p gfx.Vec2, screen image.Point) gfx.Vec2

WorldToScreen converts a world position to logical screen pixels. With PixelSnap it uses the rounded position, as the Renderer draws.

type CameraPose

type CameraPose struct {
	Pos gfx.Vec2
	// Zoom and Rotation are as in Camera (a zero Zoom means 1).
	Zoom, Rotation float32
	// Set reports whether the pose was recorded.
	Set bool
}

CameraPose is a camera's view at one tick. The zero CameraPose (Set false) means "none".

type CanvasID

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

CanvasID refers to a canvas of a Canvases. It is 8 bytes, comparable and pointer-free, so it can live in draw items and components; the zero value means "none". Freeing a canvas makes its IDs stale.

func (CanvasID) IsZero

func (id CanvasID) IsZero() bool

IsZero reports whether id is the zero CanvasID.

type Canvases

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

Canvases owns offscreen images that code outside this package fills by painting a Queue into them, and then draws with KindCanvas items. It is how a system pre-renders something that does not change every frame (the static tiles of a map chunk) into one image, so later frames queue one item instead of hundreds.

Create it once with NewCanvases, publish it as a World resource and give it to the Renderer with Renderer.SetCanvases. Like the Queue, it is used on the game goroutine only: Ebiten allows drawing into offscreen images in Update as well as in Draw.

func NewCanvases

func NewCanvases(st Stores) *Canvases

NewCanvases returns an empty set of canvases whose Paint resolves sprite and font handles through st. It allocates no Ebiten image.

func (*Canvases) Bytes

func (c *Canvases) Bytes() int64

Bytes returns the GPU memory estimate (4 bytes per pixel) of the canvases that are not freed, not counting the spare images kept for reuse.

func (*Canvases) Free

func (c *Canvases) Free(id CanvasID)

Free releases canvas id: its image is kept for reuse by New or deallocated, and id and its copies become stale. Freeing the zero or a stale ID does nothing.

func (*Canvases) Len

func (c *Canvases) Len() int

Len returns the number of canvases that are not freed.

func (*Canvases) New

func (c *Canvases) New(w, h int) CanvasID

New returns a transparent w x h canvas. It reuses the image of a freed canvas of the same size when one is kept, and allocates one otherwise.

Panics with "render: canvas size" when w or h is not positive.

func (*Canvases) Paint

func (c *Canvases) Paint(id CanvasID, q *Queue)

Paint clears canvas id and draws q into it, in q's order (Paint does not sort it). Items are drawn as by Renderer.Draw with an identity camera, so world and screen space are both canvas pixels, (0, 0) being the canvas's top-left corner; interpolation is off (Pos is used). Sprites that are not ready draw their placeholder, so paint once they are ready. Paint draws right away; it allocates nothing once its painter exists and its buffers have grown.

Panics with "render: stale canvas" when id is zero or stale.

func (*Canvases) Size

func (c *Canvases) Size(id CanvasID) image.Point

Size returns the size of canvas id in pixels, or the zero Point for the zero or a stale ID.

type Font

type Font struct {
	// Face draws and measures text. It is a *text.GoTextFace.
	Face text.Face
	// LineHeight is the distance between two baselines, in pixels.
	LineHeight float64
}

Font is a face of a FontSource at one size. The key carries the size in pixels after '#': LoadFont(sc, "fonts/ui.ttf#16").

A Font is cheap: it depends on the FontSource of the same file, so every size of a font parses the file once. (It is a dependent asset and not an asset child, because a FontSource cannot know which sizes will be asked for.)

type FontSource

type FontSource struct {
	Source *text.GoTextFaceSource
}

FontSource is a parsed TTF or OTF file, shared by every size of that font. Load it with asset.Load[FontSource]; you usually load a Font instead.

type FontSourceID

type FontSourceID = asset.Handle[FontSource]

FontSourceID is a handle to a FontSource.

type FontStore

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

FontStore resolves gfx.FontHandle values to fonts. Get one from StoresOf or FontStoreOf. It is a small value; copy it freely.

func FontStoreOf

func FontStoreOf(srv *asset.Server) FontStore

FontStoreOf returns the font store of srv. It panics like asset.StoreOf if RegisterLoaders has not run on srv.

func (FontStore) Err

func (s FontStore) Err(h gfx.FontHandle) error

Err returns why the font failed to load, or nil.

func (FontStore) Generic

func (s FontStore) Generic() *asset.Store[Font]

Generic returns the underlying generic store, for loaders and tools that work with asset.Handle[Font].

func (FontStore) Get

func (s FontStore) Get(h gfx.FontHandle) *Font

Get returns the font, or the placeholder; see asset.Store.Get. It does not allocate.

func (FontStore) Key

func (s FontStore) Key(h gfx.FontHandle) asset.Key

Key returns the key h was loaded from, or the zero Key for a zero or stale handle.

func (FontStore) Lookup

func (s FontStore) Lookup(h gfx.FontHandle) (*Font, asset.State)

Lookup is Get plus the load state; see asset.Store.Lookup.

func (FontStore) Ready

func (s FontStore) Ready(h gfx.FontHandle) bool

Ready reports whether h refers to a loaded font.

type GroupConfig

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

GroupConfig holds the layer groups of a Renderer (see Renderer.SetGroups). The zero value has no groups and is ready to use. Add groups before the first frame; Set may change a group's options at any time between frames, for example to animate Params.

func (*GroupConfig) Add

func (c *GroupConfig) Add(opts GroupOptions) GroupID

Add adds a group and returns its ID.

Panics with "render: group From > To" for an empty range and with "render: group layers overlap" when the range shares a layer with another group.

func (*GroupConfig) Len

func (c *GroupConfig) Len() int

Len returns the number of groups.

func (*GroupConfig) Options

func (c *GroupConfig) Options(id GroupID) GroupOptions

Options returns the options of group id. Panics with "render: unknown group" for an id that Add did not return.

func (*GroupConfig) Set

func (c *GroupConfig) Set(id GroupID, opts GroupOptions)

Set replaces the options of group id. Changing only Params, Shader, Blend or Clear does not allocate.

Panics like GroupConfig.Add, and with "render: unknown group" for an id that Add did not return.

type GroupID

type GroupID int

GroupID identifies a layer group of a GroupConfig. It is the index returned by GroupConfig.Add.

type GroupOptions

type GroupOptions struct {
	// From and To are the first and last render layer of the group,
	// inclusive. A one-layer group has From == To.
	From, To int16
	// Shader composites the group image. The zero handle, and a shader that
	// is loading or failed, composite it unchanged. The shader gets the
	// group image as imageSrc0 (logical screen size, src in pixels),
	// Params as its "Params" vec4 uniform and, with SampleBelow, a copy of
	// what was drawn below the group as imageSrc1.
	Shader gfx.ShaderHandle
	// Params are passed to Shader as its "Params" vec4 uniform.
	Params [4]float32
	// Blend composites the group image onto what is below:
	// BlendNormal, BlendAdditive or BlendMultiply (light maps).
	Blend Blend
	// Clear is what the group image is cleared to every frame. The zero
	// value is transparent. A light map clears to the ambient light color.
	// A group whose Clear is not transparent is composited even when no
	// item falls into it, so the ambient light still applies.
	Clear color.RGBA
	// SampleBelow copies what is on the screen below the group, before the
	// group is composited, and passes the copy to Shader as imageSrc1 (for
	// refraction or water that distorts the scene behind it). It costs one
	// screen-sized copy per frame. Ignored without a shader.
	SampleBelow bool
	// NoComposite draws the group's layers into its image and never
	// composites it onto the scene, not even an empty group with a visible
	// Clear. The image is only seen by post passes that read it with
	// [TargetGroup] (masks, displacement maps, light maps to blur first).
	// Shader, Params, Blend and SampleBelow are ignored, and the group does
	// not count in [Stats].Groups. Without a pass that reads it the group
	// is drawn for nothing.
	NoComposite bool
}

GroupOptions configures a layer group: the render layers From..To (inclusive) are drawn into an offscreen image instead of the screen, and that image is then composited onto what is below it, through Shader if one is set. A group is how a shader applies to a whole layer (water distortion, fog, a light map) instead of to one sprite.

type Item

type Item struct {
	Kind  Kind
	Space Space
	// Layer is the draw order: lower layers draw first.
	Layer int16
	// SortY orders items inside a layer configured with YSort.
	SortY float32
	// Insets are the borders of a KindNineSlice item in source pixels. They
	// sit here, next to the small fields, to keep Item from growing by
	// padding. For this kind Origin is the pivot as a fraction of Size, the
	// zero Origin being the top-left corner.
	Insets gfx.Insets

	// Sprite is the image for KindSprite. The zero handle draws the
	// placeholder.
	Sprite gfx.SpriteHandle
	// Pos is the position at the current tick. For ScreenSpace items it is
	// in logical screen pixels.
	Pos gfx.Vec2
	// PrevPos is the position at the previous tick, used when HasPrev is
	// set: the Renderer blends it to Pos by the draw alpha. Rotation and
	// scale do not blend; they keep the item small for the copy loops of
	// extract and sort.
	PrevPos gfx.Vec2
	// Rot is the rotation in radians.
	Rot float32
	// Scale multiplies the size. Extract resolves the "zero means 1" rule,
	// so the Renderer treats a zero Scale as zero.
	Scale gfx.Vec2
	// Origin is the pivot as a fraction of the sprite size. The zero Origin
	// means the sprite's own default pivot.
	Origin       gfx.Vec2
	FlipX, FlipY bool
	// Tile repeats the edges and center of a KindNineSlice item instead of
	// stretching them.
	Tile bool
	// HasPrev reports whether PrevPos is set. Without it the item is drawn
	// at Pos for every alpha, as static items should be; see
	// [Item.MovedFrom]. It sits in padding, so it costs no size.
	HasPrev bool

	// Size is the rect size, the line end offset, in X the circle radius, or
	// the size of a KindNineSlice panel (zero is the image's own size).
	Size gfx.Vec2

	// Color tints sprites and colors shapes and text. The zero Color is
	// white (see gfx.Color).
	Color gfx.Color
	Blend Blend

	// Shader draws the item through a Kage shader instead of the default
	// pipeline. The zero handle, and a shader that is loading or failed,
	// draw the item normally. The shader gets the item's image as
	// imageSrc0, Color (premultiplied) as the color argument of Fragment,
	// and Params as the "Params" vec4 uniform (see [ShaderUniformParams]).
	//
	// For KindSprite and KindCanvas the image is the sprite's frame or the
	// canvas. A KindText, KindNineSlice, KindRect, KindLine or KindCircle
	// item is first drawn white, at scale 1 and unrotated, into an
	// offscreen image with a transparent margin of 4 pixels; the shader
	// gets that image, so it sees the whole text, panel or shape. Each such
	// item is a draw call of its own.
	Shader gfx.ShaderHandle
	// Params are per-item shader parameters (a flash amount, an outline
	// color, a dissolve threshold): what they mean is up to the shader.
	Params [4]float32
	// Aux is a second image for Shader (a noise texture, a mask, a
	// palette), which the shader reads as imageSrc1; without Shader it is
	// ignored. It may have any size and may be an atlas frame. The zero
	// handle, and a sprite that is loading or failed, give no image:
	// imageSrc1At returns transparent pixels, never the placeholder. Items
	// with different Aux images are different batches.
	Aux gfx.SpriteHandle

	// Canvas is the image of a KindCanvas item. Origin is the pivot as a
	// fraction of the canvas size, the zero Origin being the top-left
	// corner; Shader draws it through a shader like a sprite. A zero or stale ID, or a Renderer without
	// canvases (see [Renderer.SetCanvases]), draws nothing.
	Canvas CanvasID

	// Text and Font are used by KindText. The queue lives for one tick, so
	// holding a string here is fine.
	Text string
	Font gfx.FontHandle
}

Item is one draw command: a plain value written by extract systems and read by the Renderer. Fields that a Kind does not use are ignored.

func (*Item) MovedFrom

func (it *Item) MovedFrom(p gfx.Vec2)

MovedFrom sets the position at the previous tick: the Renderer blends p to Pos.

type Kind

type Kind uint8

Kind selects how an Item is drawn.

const (
	KindSprite Kind = iota
	KindRect
	KindLine
	KindCircle
	KindText
	// KindCanvas draws Item.Canvas, an image pre-rendered with
	// [Canvases.Paint].
	KindCanvas
	// KindNineSlice draws Item.Sprite as a nine-slice panel of Item.Size,
	// cut by Item.Insets (see gfx.NineSlice).
	KindNineSlice
)

Kinds.

type LayerConfig

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

LayerConfig holds per-layer options. The zero value is ready to use and means "no layer is Y-sorted". It is read while sorting, so configure it before the first tick rather than during one.

func (*LayerConfig) Options

func (c *LayerConfig) Options(layer int16) LayerOptions

Options returns the options of layer.

func (*LayerConfig) Set

func (c *LayerConfig) Set(layer int16, opts LayerOptions)

Set applies opts to layer.

type LayerOptions

type LayerOptions struct {
	// YSort orders items of the layer by Item.SortY (top-down games: things
	// lower on the screen draw in front).
	YSort bool
}

LayerOptions configures how one layer is sorted.

type Layout

type Layout struct {
	// Width and Height are the logical resolution in pixels.
	Width, Height int
	// Integer makes the image scale by a whole number (pixel-perfect
	// pixel art): the logical size grows to fill the window at the largest
	// integer scale that still fits Width x Height.
	Integer bool
}

Layout computes the logical screen size to return from Ebiten's Layout method.

func (Layout) Size

func (l Layout) Size(outsideW, outsideH int) (w, h int)

Size returns the logical size for a window of outsideW x outsideH. Pass the result to the Screen resource so extract systems cull against it.

type LoaderOptions

type LoaderOptions struct {
	// TransparentPlaceholders makes missing, loading and failed assets draw
	// nothing (a transparent 1x1 image) instead of the magenta checker. Use it
	// in release builds; keep the checker in development so gaps are visible.
	TransparentPlaceholders bool
}

LoaderOptions configures RegisterLoaders.

type Pass

type Pass struct {
	// Shader runs once per pixel of Out. It gets Src as imageSrc0, the
	// Extra images as imageSrc1 to imageSrc3 and Params as its "Params" vec4
	// uniform. The zero handle, and a shader that is loading or failed, skip
	// the pass.
	//
	// The shader's src is in Src's pixels: the pass draws one quad over Out,
	// with source coordinates spanning all of Src, so a pass that writes a
	// smaller image than it reads runs once per small pixel and sees src at
	// the center of the block of Src pixels it covers. To read an input of
	// another size, map src by the sizes and add imageSrc0Origin(), because
	// Kage takes the position of imageSrcNAt in imageSrc0's texture:
	// imageSrc1At(imageSrc0Origin() +
	// (src-imageSrc0Origin())/imageSrc0Size()*imageSrc1Size()).
	Shader gfx.ShaderHandle
	// Params are passed to Shader as its "Params" vec4 uniform.
	Params [4]float32
	// Off skips the pass (a settings toggle) without removing it.
	Off bool

	// Src is the image the shader reads as imageSrc0: the chain so far
	// (zero), TargetFrame, TargetPrevious or a declared target.
	Src TargetID
	// Extra are the images read as imageSrc1 to imageSrc3; zero is unused.
	// Any input may have any size.
	Extra [3]TargetID
	// Out is the image the pass writes, replacing its pixels: the chain
	// (zero) or a declared target. A pass that writes a target leaves the
	// chain as it was. If no running pass writes the chain, the frame is
	// shown as it is. Out may not also be read by the pass.
	//
	// A skipped pass (Off, shader not loaded) writes nothing: its Out keeps
	// what it held last frame, or is transparent if it was never written.
	Out TargetID
	// contains filtered or unexported fields
}

Pass is one full-screen shader pass of a PostChain.

type PostChain

type PostChain struct {
	// Passes run in order on the frame Draw produced. Each one reads the
	// output of the previous one; the last one writes the screen. With no
	// pass that runs (none, all Off, or shaders not loaded), Draw draws
	// straight to the screen and allocates nothing.
	Passes []Pass
	// Targets are the offscreen images the passes can write and read; the
	// target at index i has the ID i+1. Declare them with [PostChain.AddTarget].
	Targets []Target
	// Final, when set, is drawn by [Renderer.DrawFinal] at window (device)
	// resolution: the shader gets the logical frame as imageSrc0 and runs
	// once per window pixel, for effects that need real pixels (CRT
	// scanlines and masks, smooth upscaling). nil, Off or a shader that is
	// not loaded draw the frame with Ebiten's default scaling.
	Final *Pass
	// Fade covers the frame with a color after Passes and before Final: a
	// screen fade or flash without a shader. Its alpha says how much (255:
	// fully covered). Unlike a Sprite tint, a zero alpha byte means no fade,
	// so the zero value does nothing; the fade costs one draw while it is on.
	Fade gfx.Color
}

PostChain is the post-processing of a Renderer (see Renderer.SetPost): full-screen shader passes over the finished frame, at logical resolution, and an optional final pass at window resolution. The zero value does nothing and is ready to use.

Game code owns the chain: set Passes up once and change a pass's Params or Off between frames (from a system: it is a World resource in game.Engine). The renderer reads it in every Draw and never copies or keeps it.

func (*PostChain) AddBloom

func (p *PostChain) AddBloom(opts BloomOptions) Bloom

AddBloom appends a bloom to the chain: the bright parts of the chain so far (or of opts.Src) are shrunk to a half and then a quarter of the screen size, blurred there and added back, so bright pixels glow. It declares three targets (half, quarter and a quarter-size scratch image) and appends five passes that run the engine's own shaders, which need no asset and are ready on the first frame.

Passes added later see the bloom; passes added earlier are what it glows. Do not remove or reorder passes before the bloom's: the returned Bloom finds its passes by index. Use Bloom.Set to retune and Bloom.SetOff to switch the effect off.

func (*PostChain) AddTarget

func (p *PostChain) AddTarget(t Target) TargetID

AddTarget declares an offscreen image for passes to write and read and returns its ID. Add targets before the first frame that uses them; do not remove or reorder them afterwards, as passes refer to them by ID.

type Queue

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

Queue is the frame's command list. Systems Push items during Update, Sort orders them, and the Renderer reads them in Draw.

The Queue is reused every tick: Reset keeps the capacity, so the steady state allocates nothing. It is not safe for concurrent use.

func (*Queue) AddCulled

func (q *Queue) AddCulled(n int)

AddCulled records that an extract system skipped n items this tick because they were outside the camera bounds. Reset clears the count; the Renderer reports it as Stats.Culled. Extract systems call it once per Run with their total, not once per item.

func (*Queue) At

func (q *Queue) At(i int) *Item

At returns the i-th item in draw order, 0 <= i < Len. Before Sort (or after a Push that followed it) this is insertion order. The pointer is valid until the next Push or Reset.

func (*Queue) Culled

func (q *Queue) Culled() int

Culled returns the number of items culled since the last Reset.

func (*Queue) Len

func (q *Queue) Len() int

Len returns the number of queued items.

func (*Queue) Push

func (q *Queue) Push(it Item)

Push appends a copy of it.

func (*Queue) Reset

func (q *Queue) Reset()

Reset empties the queue and keeps its capacity. Text strings are cleared so the queue does not keep them alive.

func (*Queue) SetMinLayer

func (q *Queue) SetMinLayer(l int16)

SetMinLayer makes Sort drop the items on layers below l and count them as culled (see Queue.Culled). The engine sets it every tick from the scene stack, so a scene that does not draw the scenes below it hides their layers. math.MinInt16 (or any value no item is below) removes the floor; the zero Queue has none. Reset keeps it.

func (*Queue) Sort

func (q *Queue) Sort(cfg *LayerConfig, sprites SpriteStore)

Sort puts the items in draw order: by layer, then by SortY inside layers that cfg marks YSort, then (when sprites is not the zero SpriteStore) by shader and then texture, so batches stay together: Ebiten only merges consecutive draws with the same source, shader and uniforms. Items that compare equal keep their insertion order. Items below the layer set by Queue.SetMinLayer are dropped first. Missing, loading and failed sprites share the placeholder's texture, and canvas items sort before the sprites of their layer (in insertion order). cfg may be nil and sprites may be the zero SpriteStore (no shader or texture ordering).

func (*Queue) Sprite

func (q *Queue) Sprite(layer int16, id gfx.SpriteHandle, pos, prev gfx.Vec2) *Item

Sprite appends a world-space sprite item with Scale (1,1) at pos, moved from prev (see Item.MovedFrom), and returns a pointer to the slot for filling in more fields. The pointer is valid until the next Push, Sprite or Reset.

type Renderer

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

Renderer turns a sorted Queue into Ebiten draw calls. Sprites and shapes are batched: consecutive unshaded ones that share a target, a source texture and a blend mode become one DrawTriangles call, consecutive shaded ones that share a target, an image, a blend mode, a shader and Params one DrawTrianglesShader call. It owns reused draw options and vertex buffers, so steady-state sprite and shape drawing allocates nothing. It has no access to the ecs World.

func NewRenderer

func NewRenderer(st Stores) *Renderer

NewRenderer returns a Renderer that resolves sprite and font handles through st. See StoresOf.

func (*Renderer) Draw

func (r *Renderer) Draw(dst *ebiten.Image, q *Queue, cam *Camera, alpha float64)

Draw renders q onto dst through cam. alpha in [0,1] blends the previous position of every item (Item.PrevPos, when HasPrev is set) and the previous view of the camera (Camera.Prev) to the current ones, so that a 60 TPS simulation looks smooth at any frame rate. q should have been sorted. Draw never reads the World and allocates nothing for sprites (shaded or not) and shapes; text may allocate. With a post chain (see Renderer.SetPost) whose passes run, the frame, including what dst held before Draw, is drawn offscreen and the passes write dst; without one Draw draws straight onto dst. PostChain.Fade is drawn over the result.

func (*Renderer) DrawFinal

func (r *Renderer) DrawFinal(screen ebiten.FinalScreen, offscreen *ebiten.Image, geoM ebiten.GeoM)

DrawFinal draws the logical frame offscreen onto the window screen, at window resolution: through PostChain.Final if it is set, not Off and loaded, else with ebiten.DefaultDrawFinalScreen. Its arguments are those of ebiten.FinalScreenDrawer, whose DrawFinalScreen should call it; game.Engine does. geoM scales and centers the frame in the window and is applied to the shader's rectangle, so imageSrc0At(src) samples the frame in logical pixels while the shader runs per window pixel (dst).

A final pass adds one to Stats.PostPasses of the frame.

func (*Renderer) SetCanvases

func (r *Renderer) SetCanvases(c *Canvases)

SetCanvases makes the Renderer draw KindCanvas items from c; nil (the default) means they draw nothing.

func (*Renderer) SetGroups

func (r *Renderer) SetGroups(g *GroupConfig)

SetGroups makes the Renderer draw the layer groups of g; nil means no groups. The Renderer reads g in every Draw, so later changes through GroupConfig.Set apply from the next frame.

func (*Renderer) SetPost

func (r *Renderer) SetPost(p *PostChain)

SetPost sets the post-processing chain Draw and DrawFinal run (nil: none). The renderer keeps the pointer and reads the chain on every frame, so changes to it apply from the next Draw.

func (*Renderer) SetTime

func (r *Renderer) SetTime(t time.Duration)

SetTime sets the value of the Time uniform (see ShaderUniformTime) for the following Draw and DrawFinal calls: t in seconds, as a float32. It starts at 0 and only changes through SetTime; game.Engine sets it every frame to the interpolated simulation time. It allocates nothing.

A float32 has about 7 significant digits, so after a few hours Time advances in steps of a millisecond or more. Shaders that animate with it should wrap it themselves (mod(Time, period)) rather than rely on long absolute values.

func (*Renderer) Stats

func (r *Renderer) Stats() Stats

Stats returns the statistics of the last Draw.

type Shader

type Shader struct {
	Shader *ebiten.Shader
}

Shader is a compiled Kage shader. Load it with LoadShader (or asset.Load[Shader]) from a .kage source file. A compile error fails the asset; use ShaderStore.Err or the Server's OnError to show it.

The Renderer passes the uniforms ShaderUniformParams and ShaderUniformTime; a shader declares only the ones it uses. A shader that declares one of them with a different type fails to load, so the mismatch never panics while drawing.

The placeholder (what a missing, loading or failed handle resolves to) has a nil Shader field, which means "no shader": draw code must treat nil as the default pipeline.

type ShaderID

type ShaderID = asset.Handle[Shader]

ShaderID is the generic handle to a Shader. The zero handle means no shader. Components and items hold the concrete gfx.ShaderHandle; see LoadShader.

type ShaderStore

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

ShaderStore resolves gfx.ShaderHandle values to shaders. Get one from StoresOf or ShaderStoreOf. It is a small value; copy it freely.

func ShaderStoreOf

func ShaderStoreOf(srv *asset.Server) ShaderStore

ShaderStoreOf returns the shader store of srv. It panics like asset.StoreOf if RegisterLoaders has not run on srv.

func (ShaderStore) Err

func (s ShaderStore) Err(h gfx.ShaderHandle) error

Err returns why the shader failed to load (for example its compile error), or nil.

func (ShaderStore) Generic

func (s ShaderStore) Generic() *asset.Store[Shader]

Generic returns the underlying generic store, for loaders and tools that work with asset.Handle[Shader].

func (ShaderStore) Get

func (s ShaderStore) Get(h gfx.ShaderHandle) *Shader

Get returns the shader, or the placeholder, whose Shader field is nil ("no shader"); see asset.Store.Get. It does not allocate.

func (ShaderStore) Key

Key returns the key h was loaded from, or the zero Key for a zero or stale handle.

func (ShaderStore) Lookup

func (s ShaderStore) Lookup(h gfx.ShaderHandle) (*Shader, asset.State)

Lookup is Get plus the load state; see asset.Store.Lookup.

func (ShaderStore) Ready

func (s ShaderStore) Ready(h gfx.ShaderHandle) bool

Ready reports whether h refers to a loaded shader.

type Space

type Space uint8

Space says what coordinates an Item is in.

const (
	// WorldSpace items are transformed by the camera.
	WorldSpace Space = iota
	// ScreenSpace items (HUD, UI) are in logical screen pixels and ignore
	// the camera.
	ScreenSpace
)

Spaces.

type Sprite

type Sprite struct {
	// Image is the cached sub-image, created once when the sprite is
	// finished: SubImage allocates, so draw code must never call it per frame.
	// It is deallocated with the texture, so keep the handle, not the image.
	Image *ebiten.Image
	// Texture is the texture the sprite is cut from, for batching sort keys.
	Texture TextureID
	// Rect is the frame's pixel rectangle inside the texture.
	Rect image.Rectangle
	// Origin is the default pivot as a fraction of Size (0..1). A component
	// may override it.
	Origin gfx.Vec2
	// Size is the size in pixels of the untrimmed frame. It equals the size of
	// Rect unless the packer trimmed transparent borders.
	Size gfx.Vec2
	// Offset is where the trimmed Rect starts inside the untrimmed frame, in
	// pixels. Zero when nothing was trimmed.
	Offset gfx.Vec2
	// contains filtered or unexported fields
}

Sprite is a drawable rectangle of a texture: either one frame of an Atlas ("chars/hero.atlas.json#idle_0") or a whole image ("ui/cursor.png").

type SpriteStore

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

SpriteStore resolves gfx.SpriteHandle values to sprites. Get one from StoresOf or SpriteStoreOf. It is a small value; copy it freely. The zero SpriteStore is "no store": only Queue.Sort accepts it.

func SpriteStoreOf

func SpriteStoreOf(srv *asset.Server) SpriteStore

SpriteStoreOf returns the sprite store of srv. It panics like asset.StoreOf if RegisterLoaders has not run on srv.

func (SpriteStore) Err

func (s SpriteStore) Err(h gfx.SpriteHandle) error

Err returns why the sprite failed to load, or nil.

func (SpriteStore) Generic

func (s SpriteStore) Generic() *asset.Store[Sprite]

Generic returns the underlying generic store, for loaders and tools that work with asset.Handle[Sprite].

func (SpriteStore) Get

func (s SpriteStore) Get(h gfx.SpriteHandle) *Sprite

Get returns the sprite, or the placeholder; see asset.Store.Get for the pointer validity rule. It does not allocate.

func (SpriteStore) Key

Key returns the key h was loaded from, or the zero Key for a zero or stale handle.

func (SpriteStore) Lookup

func (s SpriteStore) Lookup(h gfx.SpriteHandle) (*Sprite, asset.State)

Lookup is Get plus the load state; see asset.Store.Lookup.

func (SpriteStore) Ready

func (s SpriteStore) Ready(h gfx.SpriteHandle) bool

Ready reports whether h refers to a loaded sprite.

type Stats

type Stats struct {
	// Items is the number of queue items drawn.
	Items int
	// DrawCalls is the number of Ebiten draw calls issued (Ebiten may merge
	// consecutive calls into fewer GPU batches). A batch of quads (see
	// Quads) is one draw call.
	DrawCalls int
	// Quads is how many unshaded textured quads went into batched draw
	// calls: one per unshaded sprite, and one per edge of a rect or line.
	// (A circle is a mesh and a draw call of its own, not quads.)
	// Consecutive quads with the same target, source texture
	// and blend mode share one draw call.
	Quads int
	// ShadedQuads is how many items were drawn through their shader
	// (Item.Shader resolved to a loaded shader), one quad each. Consecutive
	// sprites and canvases with the same target, image (atlas frame), blend
	// mode, shader and Params share one draw call; a shaded text, nine-slice
	// or shape is always a draw call of its own, plus the calls that draw
	// it into the scratch image first (counted in DrawCalls and Quads).
	ShadedQuads int
	// ShaderDraws is how many of the draw calls went through a shader: the
	// batches of shaded quads, plus shaded layer group composites and post
	// passes.
	ShaderDraws int
	// Groups is how many layer groups were composited (see [GroupConfig]).
	// Their composite draws count in DrawCalls.
	Groups int
	// Placeholders is how many sprite items drew the placeholder sprite
	// because their handle was zero, stale, loading or failed. A steady
	// non-zero value usually means a wrong asset key.
	Placeholders int
	// Culled is how many items the extract systems skipped because they
	// were outside the camera bounds, as reported by [Queue.Culled]. It is
	// not a renderer count: culling happens in extract, not in Draw.
	Culled int
	// PostPasses is how many post-processing passes ran (see [PostChain]),
	// including the final pass of [Renderer.DrawFinal]. Each one is also a
	// draw call and a shader draw.
	PostPasses int
}

Stats describes the last Draw call.

type StatsOverlay

type StatsOverlay struct {
	// Pos is the panel's top-left corner in logical screen pixels.
	Pos image.Point
	// contains filtered or unexported fields
}

StatsOverlay draws a Stats value with the current FPS and TPS as a small text panel, for development builds:

FPS 60.0  TPS 60.0
items 1200  draws 12  quads 1190
shaded 3  groups 1
culled 340  placeholders 0

It uses Ebiten's built-in debug font, so it needs no font asset and works before any asset is loaded. Call Draw at the end of the game's Draw, after Renderer.Draw, with Renderer.Stats; game.Engine does that when its stats overlay is on.

The zero StatsOverlay is ready to use and draws at the top-left corner. Draw reuses its text buffer but converts it to a string for Ebiten, which allocates once per frame; that is fine for a debug aid and keeps Renderer.Draw itself allocation-free.

func (*StatsOverlay) Draw

func (o *StatsOverlay) Draw(dst *ebiten.Image, st Stats)

Draw renders st, ebiten.ActualFPS and ebiten.ActualTPS onto dst. It must run on the game goroutine (inside Draw), like every Ebiten draw call.

type Stores

type Stores struct {
	Sprites SpriteStore
	Fonts   FontStore
	Shaders ShaderStore
}

Stores are the asset stores the Renderer resolves item handles through. Their placeholders (see RegisterLoaders) are what a zero, stale, loading or failed handle draws, so Draw never sees a nil image or face.

func StoresOf

func StoresOf(srv *asset.Server) Stores

StoresOf returns the render stores of srv. It panics like asset.StoreOf if RegisterLoaders has not run on srv.

type Target

type Target struct {
	// Scale divides the screen size: 1 (and 0) is the screen size, 2 half,
	// 4 a quarter. A size that does not divide evenly is rounded up. The
	// image follows screen resizes. It is allocated the first frame a
	// running pass uses it, and starts transparent.
	Scale int
}

Target is an offscreen image a PostChain pass can write and later passes can read, declared with PostChain.AddTarget.

type TargetID

type TargetID int

TargetID names an image a Pass reads or writes: one of the special values TargetChain, TargetFrame and TargetPrevious, or a target declared with PostChain.AddTarget. The zero value is TargetChain.

const (
	// TargetChain is the chain so far. As a pass's Src it is the output of
	// the pass before (the frame for the first pass); as its Out it is the
	// next chain image, or the screen for the last pass that writes it. The
	// zero value of Src and Out, so a pass that sets neither works as it
	// always did. As an Extra entry zero means "unused".
	TargetChain TargetID = 0
	// TargetFrame is the frame Draw produced, as the first pass sees it. It
	// is an input only.
	TargetFrame TargetID = -1
	// TargetPrevious is what the chain showed on the previous frame (at
	// the first frame, and after a resize, the current frame). It is an
	// input only. A chain with a running pass that reads it costs two more
	// screen-sized images and one more copy per frame.
	TargetPrevious TargetID = -2
)

func TargetGroup

func TargetGroup(id GroupID) TargetID

TargetGroup is the target that names the image of layer group id (see GroupConfig): the group's items drawn over its Clear color, before its shader and blend, as the logical screen size. It is an input only (Src or an Extra entry); a pass cannot write a group. A group no item fell into reads as its Clear color, never as last frame's pixels. A group that does not exist makes Draw panic with "unknown post target".

type Texture

type Texture struct {
	// Image is the uploaded image. It is deallocated when the texture is
	// unloaded, so don't keep it across Server.Update calls; keep the handle.
	Image *ebiten.Image
	// Size is the image size in pixels.
	Size image.Point
	// Bytes is the GPU memory estimate (4 bytes per pixel), for stats.
	Bytes int64
}

Texture is a whole image on the GPU: an atlas page or a standalone picture. It is an asset type: load it with asset.Load[Texture] after RegisterLoaders. Keys name PNG or JPEG files.

type TextureID

type TextureID = asset.Handle[Texture]

TextureID is a handle to a Texture.

Jump to

Keyboard shortcuts

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