Documentation
¶
Overview ¶
Package sprite provides atlas loading, 2D sprite animation and transformation, Z-ordered batching, nine-slice drawing, masks, per-sprite visual effects, and textured 2D polylines and polygons.
Index ¶
- Constants
- 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 ColorMatrix
- type ColorStop
- type CurveStop
- type Dissolve
- type DrawCounter
- type DynamicAtlas
- func (d *DynamicAtlas) Add(name string, src core.ImageSource) (Frame, bool)
- func (d *DynamicAtlas) AddImage(name string, img image.Image) (Frame, bool)
- func (d *DynamicAtlas) Atlas(page int) *Atlas
- func (d *DynamicAtlas) Clear()
- func (d *DynamicAtlas) Frame(name string) (Frame, bool)
- func (d *DynamicAtlas) Len() int
- func (d *DynamicAtlas) MemoryBytes() int64
- func (d *DynamicAtlas) PageCount() int
- func (d *DynamicAtlas) PageOf(name string) (int, bool)
- func (d *DynamicAtlas) Release()
- func (d *DynamicAtlas) Remove(name string) bool
- type DynamicAtlasOptions
- type Effect
- type Flash
- type Frame
- type Insets
- type Line
- type LineCap
- type LineJoint
- type LineTextureMode
- type Mask
- type MemoryReporter
- type NineSlice
- type Outline
- type PaletteEntry
- type PaletteSwap
- type Polygon
- type Sprite
Examples ¶
Constants ¶
const ( // BreakTint reports a sprite or tile with a non-white tint. BreakTint = "tint" // BreakBlend reports a sprite with a non-default blend mode. BreakBlend = "blend" // BreakMask reports a sprite with an active clip mask. BreakMask = "mask" // BreakEffect reports a sprite with an active per-sprite Effect. BreakEffect = "effect" // BreakMirror reports a sprite or tile whose transform mirrors it (negative scale, flip, or diagonal flip). BreakMirror = "mirror" // BreakUnevenScale reports a sprite whose X and Y scales differ in magnitude. BreakUnevenScale = "unevenScale" // BreakAlphaChange reports a run split because opacity changed (such as full vs faded sprites or differing tile opacity). BreakAlphaChange = "alphaChange" // BreakLone reports a single eligible sprite or tile that formed a run of one and drew alone. BreakLone = "lone" // BreakImageChange reports a run split because the source image or tileset changed. BreakImageChange = "imageChange" )
Break reason names recorded in DrawCounter.Reasons when a sprite or tile cannot join a DrawAtlas submission or a run is cut short.
const MaxShaderPaletteEntries = 8
MaxShaderPaletteEntries 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.
const ReducedFlashStrength float32 = 0.2
ReducedFlashStrength caps a sprite Flash's Strength when Effect.ReduceFlashes or Batch.ReduceFlashes reports true, turning harsh strobes and solid-color silhouettes into a low-contrast tint.
Variables ¶
This section is empty.
Functions ¶
func DrawMasked ¶
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 ¶
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 ¶
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 ¶
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.
Example ¶
An Animation advances through its frames on the game's fixed step, each frame for its own duration.
package main
import (
"fmt"
"time"
"github.com/nsgo-dev/game/pkg/sprite"
"github.com/nsgo-dev/nsgo/core"
)
// heroJSON is the json-array data Aseprite exports for a two-frame run cycle tagged "run".
const heroJSON = `{
"frames": [
{"filename": "hero 0.aseprite", "frame": {"x": 0, "y": 0, "w": 16, "h": 16}, "sourceSize": {"w": 16, "h": 16}, "duration": 100},
{"filename": "hero 1.aseprite", "frame": {"x": 16, "y": 0, "w": 16, "h": 16}, "sourceSize": {"w": 16, "h": 16}, "duration": 150}
],
"meta": {"scale": "1", "frameTags": [{"name": "run", "from": 0, "to": 1, "direction": "forward"}]}
}`
func main() {
atlas, _ := sprite.LoadAtlas(core.ImageSource{URI: "asset:hero.png"}, []byte(heroJSON))
run := atlas.Animations["run"]
for range 6 {
run.Update(50 * time.Millisecond)
fmt.Print(run.Index(), " ")
}
fmt.Println()
}
Output: 0 1 1 1 0 0
func (Animation) Done ¶
Done reports whether an animation that does not loop has shown its last frame for that frame's duration.
func (Animation) Frame ¶
Frame returns the frame showing now, the zero Frame for an animation of none.
func (*Animation) Reset ¶
func (a *Animation) Reset()
Reset starts the animation over from its first frame (or its last frame when Speed is negative).
type AnimationFrame ¶
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 ¶
type Atlas struct {
// Image is the packed image, which sprites draw parts of.
Image core.ImageSource
// PageWidth and PageHeight are the packed image's pixel dimensions from meta.size, or 0 when the export omits them.
PageWidth, PageHeight int
// 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 ¶
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.
Example ¶
LoadAtlas reads a TexturePacker or Aseprite export; Aseprite's tags become Animations.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/sprite"
"github.com/nsgo-dev/nsgo/core"
)
// heroJSON is the json-array data Aseprite exports for a two-frame run cycle tagged "run".
const heroJSON = `{
"frames": [
{"filename": "hero 0.aseprite", "frame": {"x": 0, "y": 0, "w": 16, "h": 16}, "sourceSize": {"w": 16, "h": 16}, "duration": 100},
{"filename": "hero 1.aseprite", "frame": {"x": 16, "y": 0, "w": 16, "h": 16}, "sourceSize": {"w": 16, "h": 16}, "duration": 150}
],
"meta": {"scale": "1", "frameTags": [{"name": "run", "from": 0, "to": 1, "direction": "forward"}]}
}`
func main() {
atlas, err := sprite.LoadAtlas(core.ImageSource{URI: "asset:hero.png"}, []byte(heroJSON))
if err != nil {
fmt.Println(err)
return
}
f := atlas.Frames["hero 1.aseprite"]
fmt.Println(len(atlas.Frames), f.X, f.W)
run := atlas.Animations["run"]
fmt.Println(len(run.Frames), run.Loop)
}
Output: 2 16 16 2 true
type Batch ¶
type Batch struct {
// Stats, when not nil, counts the batch's draw submissions and why sprites drew on their own. Draw adds to it and never resets it.
Stats *DrawCounter
// 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
// ReduceFlashes, when set, is asked once per Draw and applies to every sprite in the batch whose Effect has an active Flash and no per-effect ReduceFlashes callback of its own: Flash.Strength is capped at ReducedFlashStrength (0.2) and saturated-red flash colors are desaturated. Pass an a11y.Assist's ReduceFlashes.
ReduceFlashes func() bool
// 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 (*Batch) Draw ¶
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 ColorMatrix ¶
type ColorMatrix [20]float32
ColorMatrix is a row-major 4x5 straight-alpha color transform.
func Brightness ¶
func Brightness(v float32) ColorMatrix
Brightness returns a matrix that adds v to red, green and blue.
func Grayscale ¶
func Grayscale() ColorMatrix
Grayscale returns a matrix that replaces red, green and blue with the color's Rec. 709 luminance, keeping alpha.
func HueRotate ¶
func HueRotate(rad float32) ColorMatrix
HueRotate returns a matrix that rotates the hue by rad radians, keeping luminance approximately.
func IdentityColorMatrix ¶
func IdentityColorMatrix() ColorMatrix
IdentityColorMatrix returns the matrix that leaves colors unchanged.
func Invert ¶
func Invert() ColorMatrix
Invert returns a matrix that inverts red, green and blue, keeping alpha.
type ColorStop ¶
ColorStop is one control point mapping normalized distance T in [0, 1] along a Line to a core.Color.
type CurveStop ¶
CurveStop is one control point mapping normalized distance T in [0, 1] along a Line to a width multiplier Value.
type Dissolve ¶
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 DrawCounter ¶
type DrawCounter struct {
// AtlasCalls counts Drawing.DrawAtlas submissions, and AtlasSprites the sprites or tiles in them.
AtlasCalls, AtlasSprites int
// SingleCalls counts sprites or tiles drawn on their own.
SingleCalls int
// LayerCalls counts whole-layer single draw submissions such as cached tilemap layers and image layers.
LayerCalls int
// Reasons counts why sprites or tiles drew on their own or a run was cut short, keyed by the Break* constants ("tint", "blend", "mask", "effect", "mirror", "unevenScale", "alphaChange", "lone" and "imageChange").
Reasons map[string]int
}
DrawCounter counts the draw submissions of the batches, tilemaps, particle emitters and scenes it is attached to, and why runs left the one-call atlas path. Draw only adds to it; call Reset once per frame for per-frame figures. A nil counter costs nothing, and under -tags release every recording method compiles to a no-op.
func (*DrawCounter) Atlas ¶
func (c *DrawCounter) Atlas(n int)
Atlas records one Drawing.DrawAtlas submission containing n sprites or tiles.
func (*DrawCounter) Batches ¶
func (c *DrawCounter) Batches() int
Batches returns the number of batched DrawAtlas submissions recorded (AtlasCalls).
func (*DrawCounter) Break ¶
func (c *DrawCounter) Break(reason string)
Break records a batch-break reason without adding a draw call (for example, when an opacity or image change splits two runs).
func (*DrawCounter) DrawCalls ¶
func (c *DrawCounter) DrawCalls() int
DrawCalls returns the total number of draw calls recorded (AtlasCalls + SingleCalls + LayerCalls).
func (*DrawCounter) Layer ¶
func (c *DrawCounter) Layer()
Layer records one whole-layer draw submission such as a cached tilemap layer or an image layer.
func (*DrawCounter) Reset ¶
func (c *DrawCounter) Reset()
Reset zeroes every count, keeping the Reasons map for zero-allocation reuse.
func (*DrawCounter) Single ¶
func (c *DrawCounter) Single(reason string)
Single records one standalone draw submission and, when reason is non-empty, adds it to Reasons.
func (*DrawCounter) Sprites ¶
func (c *DrawCounter) Sprites() int
Sprites returns the total number of sprites and tiles drawn (AtlasSprites + SingleCalls).
type DynamicAtlas ¶
type DynamicAtlas struct {
// contains filtered or unexported fields
}
DynamicAtlas packs loose, downloaded, or procedurally generated images into shared OffscreenImage atlas pages at run time so sprites drawn from them batch into Drawing.DrawAtlas calls.
Each page is exposed as an ordinary *Atlas via Atlas(i), so Batch, Animation, and scene objects use it unchanged. Adding or removing a frame invalidates only the page that changed. Placement is deterministic for a given sequence of Add and Remove calls.
func NewDynamicAtlas ¶
func NewDynamicAtlas(cx *core.Scope, opts DynamicAtlasOptions) *DynamicAtlas
NewDynamicAtlas creates an empty runtime atlas owned by cx. When cx is non-nil, each allocated page is backed by a core.OffscreenImage whose lifetime is tied to cx; disposing cx automatically releases all pages and untracks them from Memory.
func (*DynamicAtlas) Add ¶
func (d *DynamicAtlas) Add(name string, src core.ImageSource) (Frame, bool)
Add packs src under name and returns its Frame and true, or (Frame{}, false) when name is empty, the atlas is released, src's dimensions cannot be determined or exceed MaxFrame / PageSize, or MaxPages prevents allocating another page.
src may be a core.ImageSource with Pixels, encoded Data (with Size set or a registered Go image decoder), an Offscreen image, or a URI with Size set. Pixels are copied so later mutations to the caller's buffer do not alter the packed frame. Adding an existing name replaces it, updating the frame in place when its dimensions match.
func (*DynamicAtlas) AddImage ¶
AddImage packs a decoded image.Image under name and returns its Frame and true, or (Frame{}, false) when img is nil or empty, name is empty, the atlas is released, the image exceeds MaxFrame / PageSize, or MaxPages prevents allocating another page.
Pixels are copied into premultiplied RGBA so later mutations to img do not alter the packed frame. Adding an existing name replaces it, updating the frame in place when its dimensions match.
func (*DynamicAtlas) Atlas ¶
func (d *DynamicAtlas) Atlas(page int) *Atlas
Atlas returns the *Atlas for the zero-based page index, or nil when page is out of range. Its Image is synchronized with the page's retained OffscreenImage so batches, animations, and scene objects can use it directly.
func (*DynamicAtlas) Clear ¶
func (d *DynamicAtlas) Clear()
Clear removes every packed frame and resets every allocated page's packer to empty without releasing the pages themselves, invalidating only pages that held frames.
func (*DynamicAtlas) Frame ¶
func (d *DynamicAtlas) Frame(name string) (Frame, bool)
Frame looks up name across all pages and returns its Frame and true, or (Frame{}, false) when absent.
func (*DynamicAtlas) Len ¶
func (d *DynamicAtlas) Len() int
Len returns the total number of live packed frames across all pages.
func (*DynamicAtlas) MemoryBytes ¶
func (d *DynamicAtlas) MemoryBytes() int64
MemoryBytes returns the total estimated decoded RGBA8 byte footprint of all currently allocated pages.
func (*DynamicAtlas) PageCount ¶
func (d *DynamicAtlas) PageCount() int
PageCount returns the number of currently allocated atlas pages.
func (*DynamicAtlas) PageOf ¶
func (d *DynamicAtlas) PageOf(name string) (int, bool)
PageOf returns the zero-based page index holding name and true, or (-1, false) when absent.
func (*DynamicAtlas) Release ¶
func (d *DynamicAtlas) Release()
Release drops every page's OffscreenImage, removes all frames, and untracks every page from Memory. Calling Release more than once is safe.
func (*DynamicAtlas) Remove ¶
func (d *DynamicAtlas) Remove(name string) bool
Remove deletes the frame named name from its page, frees its rectangle for reuse (coalescing adjacent free spans), and invalidates only that page's OffscreenImage. It reports whether name was present.
type DynamicAtlasOptions ¶
type DynamicAtlasOptions struct {
// PageSize is the width and height of each square atlas page in points (1024 when <= 0).
PageSize int
// MaxFrame is the largest source image width or height accepted into the atlas (min(256, PageSize) when <= 0).
// Images larger than MaxFrame (or whose extruded block exceeds PageSize) are refused by Add and AddImage.
MaxFrame int
// Padding is the transparent gap in pixels kept between adjacent packed frames (clamped to >= 0).
Padding int
// Extrude is the number of pixels each frame's border is repeated outward to prevent texture bleeding (clamped to >= 0).
Extrude int
// Scale is the backing pixel scale (pixels per point) of each page's OffscreenImage (1 when <= 0).
Scale float64
// MaxPages limits the number of pages the atlas may allocate (<= 0 means unbounded).
MaxPages int
// Memory, when set, tracks each allocated page's decoded byte footprint and untracks pages on Release.
// *gamedebug.MemoryTracker implements MemoryReporter directly.
Memory MemoryReporter
// MemoryGroup names the asset group reported to Memory ("dynamic_atlas" when empty).
MemoryGroup string
}
DynamicAtlasOptions configures a DynamicAtlas. Zero fields take sensible defaults.
type Effect ¶
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
// ReduceFlashes, when set, is asked whenever Flash is evaluated (by Apply,
// Batch.Draw, or Uniforms). While it reports true, Flash.Strength is capped
// at ReducedFlashStrength (0.2) and saturated-red flash colors are
// desaturated to the gray of the same relative luminance. Pass an
// a11y.Assist's ReduceFlashes. When nil, Batch.Draw falls back to
// Batch.ReduceFlashes.
ReduceFlashes func() bool
// 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 (*Effect) Active ¶
Active reports whether e applies any visible effect. A nil or zero Effect returns false.
func (*Effect) Apply ¶
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 (*Effect) OutlinePadding ¶
OutlinePadding returns the border padding in source pixels added on each side of the sprite when Outline is active, or 0 otherwise.
func (Effect) Uniforms ¶
func (e Effect) Uniforms(frame Frame, atlasPixelScale float32, tint core.Color, alpha float32) core.Uniforms
Uniforms 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 ¶
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 ¶
Silhouette returns a full-strength Flash that draws the sprite's alpha shape in solid color c.
type Frame ¶
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
// Shapes are the frame's convex collision polygons in untrimmed frame points from the top left, wound clockwise on screen (positive signed area in Y-down space).
Shapes [][]math2d.Vec2
// Points are the frame's named image points (such as "muzzle", "hand", or "feet") in untrimmed frame points from the top left.
Points map[string]math2d.Vec2
}
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 (Frame) Point ¶
Point returns the named image point in untrimmed frame coordinates, or false when the frame has no point with that name.
type Insets ¶
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 Line ¶
type Line struct {
// Points are the polyline vertices in drawing coordinates.
Points []math2d.Vec2
// Width is the base stroke width in points. A non-positive or non-finite Width draws nothing.
Width float32
// WidthCurve optionally scales Width along normalized arc length [0, 1]. Empty keeps 1.
WidthCurve []CurveStop
// Color is the uniform color used when Gradient is empty. Zero draws opaque white.
Color core.Color
// Gradient optionally interpolates vertex colors along normalized arc length [0, 1].
// When non-empty, Gradient overrides Color.
Gradient []ColorStop
// Texture is the image mapped onto the line when TextureMode is LineTextureTile or LineTextureStretch.
Texture core.ImageSource
// TextureMode controls whether Texture is ignored (LineTextureNone), tiled (LineTextureTile), or stretched (LineTextureStretch).
TextureMode LineTextureMode
// Joint controls how interior corners connect (LineJointSharp, LineJointBevel, or LineJointRound).
Joint LineJoint
// BeginCap and EndCap control the start and end caps when Closed is false.
BeginCap, EndCap LineCap
// Closed connects the last point back to the first into a closed loop and omits caps.
Closed bool
// MiterLimit caps the miter-to-half-width ratio for LineJointSharp before falling back to bevel. Non-positive defaults to 2.
MiterLimit float32
// RoundPrecision is the segment count per quarter-turn (or semicircle cap) for round joints and caps. Non-positive defaults to 8 (clamped to [1, 64]).
RoundPrecision int
// contains filtered or unexported fields
}
Line draws a thick, optionally textured and gradient-colored polyline as a cached triangle mesh through Drawing.DrawVertices.
The mesh is rebuilt lazily only when points or styling fields change. Mutating Points, WidthCurve, or Gradient in place is detected automatically on the next Draw, Vertices, or Bounds call; when nothing changes, Vertices and Bounds allocate nothing and Draw submits the cached triangle list in one DrawVertices call.
Example ¶
A Line builds a cached triangle mesh for a thick polyline and draws it via Drawing.DrawVertices.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/math2d"
"github.com/nsgo-dev/game/pkg/sprite"
"github.com/nsgo-dev/nsgo/core"
)
func main() {
l := &sprite.Line{
Points: []math2d.Vec2{{X: 0, Y: 10}, {X: 40, Y: 10}, {X: 40, Y: 50}},
Width: 8,
Color: core.RGB(0xe76f51),
Joint: sprite.LineJointBevel,
BeginCap: sprite.LineCapBox,
EndCap: sprite.LineCapBox,
}
d := core.NewDrawing(nil)
l.Draw(d)
fmt.Println(len(d.Ops), len(l.Vertices())/3)
}
Output: 1 9
func (*Line) Draw ¶
Draw draws the polyline into d using Drawing.DrawVertices. A nil receiver, nil drawing, fewer than two distinct finite points, or non-positive width draws nothing.
func (*Line) Vertices ¶
func (l *Line) Vertices() []core.CanvasVertex
Vertices returns the cached triangle list for l, rebuilding only when inputs changed. The returned slice aliases the cache and must not be modified by the caller.
type LineCap ¶
type LineCap uint8
LineCap controls the shape drawn at the open start and end of a Line.
type LineJoint ¶
type LineJoint uint8
LineJoint controls how consecutive segments of a Line meet at interior corners.
const ( // LineJointSharp joins corners with a miter, falling back to bevel beyond MiterLimit. LineJointSharp LineJoint = iota // LineJointBevel connects the outer corners of consecutive segments with a flat bevel. LineJointBevel // LineJointRound connects the outer corners of consecutive segments with a circular arc. LineJointRound )
type LineTextureMode ¶
type LineTextureMode uint8
LineTextureMode controls how Line.Texture maps onto a Line's triangle mesh.
const ( // LineTextureNone ignores Texture and draws a solid or gradient-colored line. LineTextureNone LineTextureMode = iota // LineTextureTile repeats Texture along the line's arc length. LineTextureTile // LineTextureStretch stretches Texture once from the start of the line to its end. LineTextureStretch )
func (LineTextureMode) String ¶
func (m LineTextureMode) String() string
String returns "none", "tile", or "stretch".
type Mask ¶
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 ¶
CircleMask returns a mask that clips drawing to the circle centered at (cx, cy) with radius r.
func EllipseMask ¶
EllipseMask returns a mask that clips drawing to the ellipse centered at (cx, cy) with radii rx and ry.
func PolygonMask ¶
PolygonMask returns a mask that clips drawing to the closed polygon formed by points.
type MemoryReporter ¶
type MemoryReporter interface {
// TrackAtlasPage records or updates a dynamic atlas page's decoded byte footprint in group.
TrackAtlasPage(group, name string, bytes int64)
// UntrackAtlasPage removes a previously tracked dynamic atlas page from group.
UntrackAtlasPage(group, name string)
}
MemoryReporter receives page allocation and release notifications from a DynamicAtlas. *gamedebug.MemoryTracker implements this interface directly.
type NineSlice ¶
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 (*NineSlice) Draw ¶
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 ¶
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 ¶
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 ¶
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 Polygon ¶
type Polygon struct {
// Points are the polygon outline vertices in drawing coordinates.
Points []math2d.Vec2
// Color fills the polygon (when Texture is empty) or tints Texture and VertexColors.
// Zero draws opaque white.
Color core.Color
// VertexColors optionally sets a per-vertex color matching Points order.
// When shorter than Points, the last entry repeats for remaining vertices.
VertexColors []core.Color
// Texture is an optional image mapped onto the polygon.
Texture core.ImageSource
// UV optionally specifies explicit texture coordinates (in image points) per vertex.
// When nil or shorter than Points, UVs are derived from Points using TextureOffset,
// TextureRotation, and TextureScale.
UV []math2d.Vec2
// TextureOffset shifts derived UVs in texture points.
TextureOffset math2d.Vec2
// TextureRotation rotates the texture clockwise in radians when deriving UVs.
TextureRotation float32
// TextureScale scales the texture in canvas points when deriving UVs (2 draws the
// texture twice as large). Non-positive defaults to 1.
TextureScale float32
// Invert fills the region outside Points up to Points' bounding box expanded by
// InvertBorder instead of filling the interior.
Invert bool
// InvertBorder is the padding around Points' bounding box when Invert is true.
// Non-positive defaults to 100.
InvertBorder float32
// contains filtered or unexported fields
}
Polygon draws a filled 2D polygon (convex, concave, or inverted) as a cached triangle mesh through Drawing.DrawVertices.
It supports solid color fills (Color), per-vertex color gradients (VertexColors), and textured fills with either explicit per-vertex UVs (UV, in texture points) or derived UVs transformed by TextureOffset, TextureRotation, and TextureScale. Derived and repeating UVs are tiled cleanly across texture boundaries so repeating terrain fills render identically on every NSGo target.
The mesh is rebuilt lazily only when points or styling fields change. When nothing changes, Vertices and Bounds allocate nothing and Draw submits the cached triangle list in one DrawVertices call.
Example ¶
A Polygon triangulates concave outlines into a cached triangle mesh drawn via Drawing.DrawVertices.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/math2d"
"github.com/nsgo-dev/game/pkg/sprite"
"github.com/nsgo-dev/nsgo/core"
)
func main() {
p := &sprite.Polygon{
Points: []math2d.Vec2{
{X: 0, Y: 0}, {X: 40, Y: 0}, {X: 40, Y: 16},
{X: 16, Y: 16}, {X: 16, Y: 40}, {X: 0, Y: 40},
},
Color: core.RGB(0x2a9d8f),
}
d := core.NewDrawing(nil)
p.Draw(d)
fmt.Println(len(d.Ops), len(p.Vertices())/3)
}
Output: 1 4
func (*Polygon) Draw ¶
Draw draws the polygon into d using Drawing.DrawVertices. A nil receiver, nil drawing, fewer than three points, or non-finite inputs draw nothing.
func (*Polygon) Vertices ¶
func (p *Polygon) Vertices() []core.CanvasVertex
Vertices returns the cached triangle list for p, rebuilding only when inputs changed. The returned slice aliases the cache and must not be modified by the caller.
type Sprite ¶
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.
Example ¶
A Sprite places a frame in the world; its Bounds account for position, origin and scale.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/sprite"
)
func main() {
s := sprite.NewSprite(sprite.Frame{W: 16, H: 16, Width: 16, Height: 16})
s.X, s.Y = 100, 50
s.OriginX, s.OriginY = 8, 16 // the bottom middle of the 16x16 frame sits at (X, Y)
s.ScaleX, s.ScaleY = 2, 2
fmt.Println(s.Bounds())
}
Output: {84 18 32 32}
func NewSprite ¶
NewSprite 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 (Sprite) Bounds ¶
Bounds 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 (Sprite) Origin ¶
Origin returns the sprite's origin (OriginX, OriginY) in its untrimmed frame.
func (Sprite) PointWorld ¶
PointWorld returns the named image point of s.Frame transformed into world (drawing) coordinates, with FlipX, FlipY, OriginX, OriginY, ScaleX, ScaleY, Rotation, and (X, Y) applied. It returns (zero, false) when s.Frame has no point with that name.
func (Sprite) ShapesWorld ¶
ShapesWorld returns s.Frame.Shapes transformed into world (drawing) coordinates with FlipX, FlipY, OriginX, OriginY, ScaleX, ScaleY, Rotation, and (X, Y) applied. When the transform mirrors the sprite (negative determinant), each polygon's vertices are reversed so every polygon keeps clockwise winding in Y-down screen space. It returns nil when s.Frame has no shapes, scale is zero, or the transform is non-finite.