La référence API provient des commentaires de documentation Go du code source et est rédigée en anglais.
package sprite
import "github.com/nsgo-dev/game/pkg/sprite"Index
- Constantes
- func DrawMasked(d *core.Drawing, mask Mask, draw func(*core.Drawing))
- func EffectProgram() (*core.ShaderProgram, error)
- func EffectShader(atlas *Atlas, s Sprite) (core.Shader, error)
- type Animation
- type AnimationFrame
- type Atlas
- type Batch
- type Dissolve
- type Effect
- type Flash
- type Frame
- type Insets
- type Mask
- type NineSlice
- type Outline
- type PaletteEntry
- type PaletteSwap
- type Sprite
Constantes
const MaxShaderPaletteEntries = 8MaxShaderPaletteEntries is the maximum number of PaletteSwap entries bound to the GPU sprite effect shader (EffectProgram). CPU rendering in Batch.Draw supports an arbitrary number of entries.
Fonctions
func DrawMasked(d *core.Drawing, mask Mask, draw func(*core.Drawing))DrawMasked clips d to mask, runs draw, and restores d's state. A zero Mask runs draw without clipping; a mask with no area skips draw.
func EffectProgram() (*core.ShaderProgram, error)EffectProgram returns the compiled Kage GPU shader program for per-sprite flash, silhouette, alpha outline, dissolve and palette swap. It compiles on first call so apps that do not use GPU sprite shaders do not link the shader compiler.
func EffectShader(atlas *Atlas, s Sprite) (core.Shader, error)EffectShader returns a core.Shader node that renders s through EffectProgram on the GPU, reading atlas.Image as image0 (and Dissolve.Noise as image1 when set). It works with URI atlases as well as pixel buffers and embedded bytes on GPU-backed targets (Metal, Direct3D 11, OpenGL, GLES 3.0 and WebGL 2).
The returned Shader's Style sets Width and Height to the sprite's scaled frame size plus any outline padding; callers position it in their layout or override Uniforms entries with AnimatedNode values.
Types
type Animation struct {
// Frames are the frames it plays, in order.
Frames []AnimationFrame
// Loop starts it over after its last frame; without it, it stays on the last frame and is done.
Loop bool
// Speed scales playback rate; 0 plays at 1x, positive values play forward, and negative values play in reverse.
Speed float32
// OnEvent, if set, is called with the frame's Event and index whenever playback enters a frame that names an Event.
OnEvent func(event string, frameIndex int)
// contains filtered or unexported fields
}Animation plays frames one after another, each for its own duration, moved on by Update with a game.Loop's fixed steps.
An Animation is a value that keeps where it is in its frames, so each sprite plays its own copy of one: copy it from an Atlas's Animations, or write one by hand.
func (a Animation) Done() boolDone reports whether an animation that does not loop has shown its last frame for that frame's duration.
func (a Animation) Frame() FrameFrame returns the frame showing now, the zero Frame for an animation of none.
func (a Animation) Index() intIndex returns the index in Frames of the frame showing now.
func (a *Animation) Reset()Reset starts the animation over from its first frame (or its last frame when Speed is negative).
func (a *Animation) Update(dt time.Duration)Update moves the animation on by dt, past as many frames as dt covers, calling OnEvent for each frame entered that names an Event. A looping animation whose frames add up to no time stays on its first frame.
func (a *Animation) UpdateEvents(dt time.Duration) []stringUpdateEvents moves the animation on by dt as Update does and returns the Event names of the frames entered during the step, in order.
type AnimationFrame struct {
Frame Frame
Duration time.Duration
// Event is an optional cue name fired when playback enters this frame.
Event string
}AnimationFrame is one frame of an animation and how long it shows.
type Atlas struct {
// Image is the packed image, which sprites draw parts of.
Image core.ImageSource
// Frames are the atlas's pictures by name.
Frames map[string]Frame
// Animations are the atlas's animations by name: an Aseprite export's frame tags. Copy one to play it.
Animations map[string]Animation
// Slices are the atlas's nine-slice insets by name: an Aseprite export's nine-slice entries in meta.slices.
Slices map[string]Insets
// contains filtered or unexported fields
}Atlas is an image that packs many pictures, and the frames that say where each one is.
LoadAtlas reads the JSON a sprite packer exports with the image. A game can also write the table by hand as an Atlas literal.
func LoadAtlas(img core.ImageSource, data []byte) (*Atlas, error)LoadAtlas reads the JSON atlas data that TexturePacker ("JSON (Hash)" and "JSON (Array)") or Aseprite (json-hash and json-array) exports for img, the image it packed.
Its rectangles are in the image's pixels, which it divides by the export's meta.scale, so img measures its points as a 1x image does. TexturePacker's per-frame pivot becomes the frame's PivotX and PivotY, in points of the untrimmed picture. Aseprite's frame tags become Animations, each frame for the duration the export gives it, in the tag's direction, looping unless the tag has a repeat count; nine-slice entries in meta.slices become Slices. Frames a packer rotated are refused: export with rotation off.
Its errors are *loaderr.Error values that give the line and field of the problem and how to fix it; a caller that read data from a file names it with loaderr.WithFile.
type Batch struct {
// Atlas is where the sprites' frames are.
Atlas *Atlas
// Sprites are the sprites it draws.
Sprites []*Sprite
// Mask, if set, clips the whole batch to a shape in the drawing's coordinates.
Mask *Mask
// contains filtered or unexported fields
}Batch draws sprites of one atlas into a drawing, in Z order. A batch with no Atlas draws nothing.
func (b *Batch) Draw(d *core.Drawing)Draw draws the batch's sprites into d, lowest Z first, and leaves d's state as it found it.
Consecutive sprites (in Z order) that are only moved, turned and scaled evenly, with the default blend, no tint, no mask and no active effect of their own, draw with one Drawing.DrawAtlas. A run of sprites at full opacity keeps the drawing's alpha, as a lone such sprite does; a run of faded sprites draws between Save and Restore with the alpha set to 1, so that each sprite's Alpha replaces the drawing's, as Sprite.Alpha says. A sprite that is mirrored, scaled unevenly, tinted, blended, masked or has an active effect, and a run of one, draws on its own, between Save and Restore when it turns, mirrors, fades, blends or clips.
type Dissolve struct {
// Threshold is the dissolve progress in [0, 1]. Values <= 0 or NaN leave
// the sprite intact; values >= 1 dissolve every pixel to transparent.
Threshold float32
// EdgeWidth is the width of the glowing edge above Threshold, in [0, 1].
// Surviving pixels whose noise lies in [Threshold, Threshold+EdgeWidth)
// are blended toward EdgeColor.
EdgeWidth float32
// EdgeColor is the dissolve front color when EdgeWidth > 0. Its alpha sets
// the blend strength over surviving edge pixels.
EdgeColor core.Color
// Seed selects the deterministic built-in noise pattern when Noise is nil.
Seed uint32
// Scale controls the spatial cell size of the built-in noise in source
// pixels. Values <= 1 (or NaN) sample per-pixel hash noise; larger values
// interpolate smooth value-noise cells.
Scale float32
// Noise is an optional grayscale noise image sampled in [0, 1] across the
// frame. When nil, deterministic value noise seeded by Seed is used.
Noise image.Image
}Dissolve progressively erodes a sprite's pixels as Threshold advances from 0 (intact) to 1 (fully dissolved), optionally coloring a glowing band along the dissolve front.
type Effect struct {
// Flash blends sprite RGB toward a solid color (or silhouette at Strength 1).
Flash Flash
// Outline draws a solid-color alpha border around opaque sprite pixels.
Outline Outline
// Dissolve erodes sprite pixels against deterministic or custom noise.
Dissolve Dissolve
// PaletteSwap remaps source colors per sprite.
PaletteSwap PaletteSwap
// Custom, if set, runs last on each pixel of the sprite's frame buffer.
// x and y are source-pixel coordinates relative to the unpadded frame's
// top-left (outside [0, w) x [0, h) inside Outline padding); w and h are
// the unpadded frame dimensions in source pixels. r, g, b, a are
// premultiplied channels in [0, 1]; the returned premultiplied channels
// are clamped to valid premultiplied [0, 1] values.
Custom func(x, y, w, h int, r, g, b, a float32) (nr, ng, nb, na float32)
}Effect describes per-sprite visual effects applied to one Sprite's pixels before compositing onto a drawing, leaving neighboring sprites and anything drawn under the sprite unchanged.
Its zero value applies no effect, so a Sprite with a nil or inactive Effect remains on Batch's DrawAtlas fast path. Multiple stages may be combined on one Effect; they run in deterministic order:
- PaletteSwap (matches and remaps source atlas colors)
- Sprite.Tint (multiplies base sprite color when Tint is also set)
- Dissolve (discards pixels below threshold and tints the dissolve edge)
- Flash (blends RGB toward a solid color or silhouette, preserving alpha)
- Outline (draws a solid border around opaque pixels with padding)
- Custom (optional per-pixel hook over premultiplied RGBA)
Parameters may change every frame. Batch reuses per-slot RGBA pixel buffers across frames so changing parameters does not leak memory.
func (e *Effect) Active() boolActive reports whether e applies any visible effect. A nil or zero Effect returns false.
func (e *Effect) Apply(src image.Image, frame Frame) (out *image.RGBA, pad int)Apply renders frame of src through e into a new premultiplied *image.RGBA, returning the image and the outline padding in source pixels added on each side. It returns (nil, 0) if src is nil or frame has non-positive dimensions.
func (e *Effect) OutlinePadding() intOutlinePadding returns the border padding in source pixels added on each side of the sprite when Outline is active, or 0 otherwise.
func (e Effect) Uniforms(frame Frame, atlasPixelScale float32, tint core.Color, alpha float32) core.UniformsUniforms builds the core.Uniforms map for EffectProgram from e, frame, atlasPixelScale (pixels per point; values <= 0 default to 1), tint and alpha. Callers may replace individual keys such as "FlashStrength" or "DissolveThreshold" with a core.AnimatedNode to animate on the platform's frame clock with no commit per frame.
type Flash struct {
// Color is the target flash or silhouette color. Its RGB channels set the
// color; the zero Color is black.
Color core.Color
// Strength is the blend amount in [0, 1].
Strength float32
}Flash blends a sprite's non-transparent RGB toward Color by Strength in [0, 1] while preserving each pixel's alpha. Strength <= 0 (or NaN) disables the flash; Strength >= 1 draws a solid-color silhouette.
func Silhouette(c core.Color) FlashSilhouette returns a full-strength Flash that draws the sprite's alpha shape in solid color c.
type Frame struct {
// Name is the frame's name in the atlas.
Name string
// X, Y, W and H are the part of the atlas's image the frame draws, in the image's points.
X, Y, W, H float32
// OffsetX and OffsetY are where that part sits in the untrimmed picture, 0 for a frame packed untrimmed.
OffsetX, OffsetY float32
// Width and Height are the untrimmed picture's size, which sprites place and flip the frame in: W and H for a frame packed untrimmed.
Width, Height float32
// PivotX and PivotY are the frame's pivot in the untrimmed picture, in points from its top left: TexturePacker's per-frame pivot, or 0 when the export gives none. NewSprite puts the sprite's origin here.
PivotX, PivotY float32
}Frame is one picture in an atlas: a part of its image, which a packer may have trimmed of the transparent border the picture had.
func (f Frame) Offset() math2d.Vec2Offset returns the trimmed frame's offset inside the untrimmed picture.
func (f Frame) Rect() math2d.RectRect returns the frame's source rectangle in the atlas image.
type Insets struct {
Left, Top, Right, Bottom float32
}Insets are the margins kept unscaled around the edges of a nine-slice frame, in the frame's points.
type Mask struct {
// contains filtered or unexported fields
}Mask clips drawing to a rectangle, circle, ellipse, or polygon in the drawing's coordinates.
Its zero value leaves drawing unmasked. A mask whose shape has no area (a non-positive rectangle or radius, or a polygon of fewer than three points) clips everything drawn through it.
func CircleMask(cx, cy, r float32) MaskCircleMask returns a mask that clips drawing to the circle centered at (cx, cy) with radius r.
func EllipseMask(cx, cy, rx, ry float32) MaskEllipseMask returns a mask that clips drawing to the ellipse centered at (cx, cy) with radii rx and ry.
func PolygonMask(points []core.Point) MaskPolygonMask returns a mask that clips drawing to the closed polygon formed by points.
func RectMask(b core.Bounds) MaskRectMask returns a mask that clips drawing to the rectangle b.
type NineSlice struct {
// Image is the packed image that holds Frame.
Image core.ImageSource
// Frame is the part of Image to slice.
Frame Frame
// Insets are the margins on each side of Frame that stay unscaled.
Insets Insets
// TileCenter repeats the center region at its natural size instead of stretching it.
TileCenter bool
}NineSlice draws a frame into any rectangle while keeping its four corners unscaled and stretching its edges and center to fill the space.
func (n *NineSlice) Draw(d *core.Drawing, x, y, width, height float32)Draw draws the nine-slice into d across the rectangle x, y, width, height, skipping any slice whose source or target dimension is zero.
When width is smaller than Left+Right or height is smaller than Top+Bottom, the margins shrink proportionally to fit and the middle spans are omitted.
type Outline struct {
// Color is the outline color. Its alpha sets the outline opacity; a Color
// with alpha 0 draws no outline.
Color core.Color
// Thickness is the border width in source pixels, clamped to [0, 64].
// Values <= 0 or NaN disable the outline; values in (0, 1) draw a 1-pixel
// border with opacity scaled by Thickness so outlines can animate smoothly.
Thickness float32
// AlphaThreshold is the minimum pixel alpha in (0, 1] treated as inside
// the sprite silhouette. Zero (or NaN) treats any non-transparent pixel
// (alpha >= 1/255) as inside.
AlphaThreshold float32
}Outline draws a solid-color border around a sprite's opaque pixels without clipping at the frame edge or sampling adjacent frames in the atlas.
type PaletteEntry struct {
// From is the straight sRGB source color to match.
From core.Color
// To is the replacement color. Its alpha scales the matched pixel's alpha,
// so an opaque core.RGB preserves the original pixel's opacity.
To core.Color
}PaletteEntry maps one straight sRGB source color to a replacement color in a PaletteSwap.
type PaletteSwap struct {
// Entries are checked in order; the first match wins.
Entries []PaletteEntry
// Tolerance is the maximum per-channel 8-bit RGB difference allowed for a
// match. Zero requires an exact 8-bit match.
Tolerance uint8
}PaletteSwap remaps sprite colors using an ordered table of PaletteEntry replacements.
type Sprite struct {
// Frame is the picture it draws now; a zero Frame draws nothing.
Frame Frame
// X and Y are where its origin goes in the drawing.
X, Y float32
// OriginX and OriginY are the point of the untrimmed frame, in its points from its top left, that sits at X, Y and that it turns and scales about.
OriginX, OriginY float32
// Rotation turns it about its origin, in radians, clockwise on the screen.
Rotation float32
// ScaleX and ScaleY scale it about its origin; a negative one mirrors it there.
ScaleX, ScaleY float32
// FlipX and FlipY mirror the picture inside its untrimmed frame, left to right and top to bottom, before it is placed, so the origin keeps its place in the frame's box.
FlipX, FlipY bool
// Alpha is its opacity, from 0, which draws nothing, to 1. It replaces the drawing's alpha for the sprite, as Drawing.SetAlpha does.
Alpha float32
// Tint multiplies each of the picture's sRGB and alpha channels by the matching channel of a color before the sprite is composited, as Drawing.DrawTintedImageFrom does: core.RGB(0xff0000) keeps only its red, and a tint's alpha fades it on top of Alpha. Transparent pixels stay transparent, so the tint never reaches what is drawn under the sprite. The zero value, like opaque white, leaves the picture as it is, and any other tint with alpha 0 draws nothing. To fade a sprite out, lower Alpha rather than the tint's alpha: a tint that reaches transparent black is the zero value and draws the picture unchanged.
Tint core.Color
// Blend is how the sprite mixes with what is already in the drawing, as Drawing.SetComposite does; the zero value is CompositeSourceOver.
Blend core.CompositeOp
// Mask, if set, clips the sprite to a shape in the drawing's coordinates before drawing it.
Mask *Mask
// Effect, if set, applies per-sprite visual effects (solid-color flash or silhouette, alpha outline, dissolve, palette swap, or a custom pixel hook) to this sprite's pixels alone, leaving neighboring sprites and anything drawn under the sprite unchanged. A nil or inactive Effect keeps the sprite on Batch's DrawAtlas fast path.
Effect *Effect
// Z orders the sprites of a batch: a higher Z draws over a lower one, and sprites with the same Z draw in the batch's order.
Z int
}Sprite is a frame of an atlas placed in a drawing: moved, turned, scaled, flipped, faded, tinted, blended and masked about its origin.
Its zero value draws nothing, as its scale and alpha are 0: NewSprite returns one at full size and opacity. Nor does a sprite whose position, origin, rotation, scale or alpha is NaN or infinite.
Tint recolors only the sprite's own pixels, leaving what is drawn under it unchanged; Blend sets how the sprite mixes with what is already drawn under it, as Drawing.SetComposite does.
func NewSprite(f Frame) SpriteNewSprite returns a sprite of f at full size and opacity, its origin at the frame's pivot (the top left when f has none).
func (s Sprite) Bounds() math2d.RectBounds returns the axis-aligned bounding rectangle of the sprite's untrimmed frame in the drawing, or the zero Rect when the sprite has an empty frame or zero scale.
func (s Sprite) Origin() math2d.Vec2Origin returns the sprite's origin (OriginX, OriginY) in its untrimmed frame.
func (s Sprite) Pos() math2d.Vec2Pos returns the sprite's position (X, Y) in the drawing.
func (s Sprite) Scale() math2d.Vec2Scale returns the sprite's scale (ScaleX, ScaleY).
func (s Sprite) Transform() math2d.AffineTransform returns the 2D affine transform taking a point of the untrimmed frame to the drawing: mirrored in the frame's box when flipped, moved so the origin is at (0, 0), scaled, turned and moved to (X, Y).