animclip

package
v0.4.0-rc.3 Latest Latest
Warning

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

Go to latest
Published: Dec 4, 2026 License: Apache-2.0 Imports: 23 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 animclip is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.

Package animclip plays animation clips, the resource files of type animation that key any registered property of scene objects on a timeline.

Properties

A clip track names its property as written in the scene file: an object field such as "x", "rotation", "alpha" or the discrete atlas frame property "sprite.frame" (ObjectProperties lists them), or a registered component field written "component.field", such as "body.speed". Component fields are keyable when a sceneformat.ComponentRegistry registers them with a numeric or bool kind; a string field has no number to key. Lookup resolves a name and Check checks a whole clip against a registry: every property must resolve, numeric tracks must hold values their property can take (0 or 1 for a bool, a whole number for an int, inside the field's range), and sprite.frame tracks must hold discrete frame keys.

Flipbook clips

FromAsepriteTag and FromSpriteAnimation build a sprite.frame clip matching an Aseprite tag's frames, exact durations and loop mode; FromFrames builds a clip from a run of atlas frame names at a fixed frame rate.

Playing

NewPlayer turns a clip into a tween.Timeline: one tween per pair of neighboring keys, so playback, seeking, looping and the clip's events run on the same deterministic clock as every other timeline. A Binder connects each track to what it drives; BindDoc writes into a sceneformat.SceneDoc and BindScene into a sceneformat.BuiltScene, keeping its sprites and their atlas frames in step, and a game can bind its own state with a Binder of its own.

The editor previews a clip with the same Player and BindScene, so a clip keyed in the editor plays the same values at the same times in the game.

Example
package main

import (
	"fmt"

	"github.com/nsgo-dev/game/pkg/animclip"
)

func main() {
	fmt.Println(animclip.PropertySpriteFrame)
}
Output:
sprite.frame

Index

Examples

Constants

View Source
const AnyState = "*"

AnyState is the special TransitionDoc.From value matching any active state other than TransitionDoc.To.

View Source
const MaxNestedClipDepth = 16

MaxNestedClipDepth caps nested clip recursion depth to prevent runaway nesting chains.

View Source
const PropertySpriteFrame = "sprite.frame"

PropertySpriteFrame is the discrete object property that steps a sprite's atlas frame name without interpolation.

View Source
const PropertyTint = "tint"

PropertyTint is the object color property that multiplies a sprite's RGBA channels.

View Source
const StateMachineSchemaComment = "# yaml-language-server: $schema=" + StateMachineSchemaURL

StateMachineSchemaComment is the first line EncodeStateMachine writes, pointing YAML language servers at StateMachineSchemaURL.

View Source
const StateMachineSchemaURL = "https://nsgo.games/schemas/states.v1.json"

StateMachineSchemaURL is where the JSON Schema of version 1 sprite state machine documents is published.

View Source
const StateMachineVersion = 1

StateMachineVersion is the schema version of *.states.yaml files this package reads and writes.

Variables

This section is empty.

Functions

func BindScreenAnimations

func BindScreenAnimations(screen *gameui.BuiltScreen, clips ClipResolver) error

BindScreenAnimations loads every clip declared in screen.Doc.Animations from clips, validates and binds each against ScreenProperties and BindScreen, and registers them on screen so screen.Play(name) plays them and delivers clip events to screen.OnEvent.

func Check

Check checks clip against reg: every track's property must resolve with Lookup, KindFrame tracks must hold valid frame keys, and numeric tracks must hold keys whose values their property can take (CheckValue). The error names the track's target and property.

func CheckClips

func CheckClips(clip *resource.Animation, clipPath string, reg *sceneformat.ComponentRegistry, clips ClipResolver) error

CheckClips checks clip (at clipPath, which may be empty for an anonymous root clip) against reg and recursively resolves every nested clip in clip.Clips through clips, refusing missing or invalid clips, cycles (such as A -> A or A -> B -> A), and nesting deeper than MaxNestedClipDepth.

func CheckClipsProps

func CheckClipsProps(clip *resource.Animation, clipPath string, props []Property, clips ClipResolver) error

CheckClipsProps checks clip (at clipPath) against an explicit property set props and recursively validates nested clips in clip.Clips through clips, refusing cycles and nesting deeper than MaxNestedClipDepth.

func CheckProps

func CheckProps(clip *resource.Animation, props []Property) error

CheckProps checks clip against an explicit property set (such as ScreenProperties): every track's property must exist in props, KindFrame tracks must hold valid frame keys, and numeric tracks must hold keys whose values their property can take (CheckValue).

func ColorValue

func ColorValue(c core.Color) float64

ColorValue packs a 32-bit RGBA core.Color into a lossless float64 for Binder callbacks.

func Connect

func Connect(sm *StateMachine, signals *sceneformat.Signals, objectID string) error

Connect wires sm to signals for objectID:

  • registers sm on signals (signals.BindAnimator) so the built-in "animator" component's setState and trigger handlers drive sm;
  • emits "animator.stateChanged" with sceneformat.AnimatorStateChangedEvent{ObjectID, From, To} on every state transition;
  • emits "animator.clipEvent" with sceneformat.AnimatorClipEvent{ObjectID, State, Name} whenever the active clip crosses a named cue event.

Connect does not overwrite sm.OnTransition or sm.OnEvent; both Go callbacks and scene signals fire together.

func EncodeStateMachine

func EncodeStateMachine(doc *StateMachineDoc) ([]byte, error)

EncodeStateMachine validates doc and writes deterministic 2-space YAML preceded by StateMachineSchemaComment.

func FormatColor

func FormatColor(c core.Color) string

FormatColor formats a core.Color canonically as "#rrggbb" when opaque or "#rrggbbaa" otherwise.

func FromAsepriteTag

func FromAsepriteTag(atlas *sprite.Atlas, tag string) (*resource.Animation, error)

FromAsepriteTag creates an animation clip from the named Aseprite frame tag in atlas, matching the tag's frame sequence (direction and repeat count), exact frame durations and loop mode.

func FromFrames

func FromFrames(name string, frames []string, fps float64, loop bool) (*resource.Animation, error)

FromFrames creates an animation clip that steps through frames at a fixed frame rate fps (frames per second) on a discrete sprite.frame track.

func FromSpriteAnimation

func FromSpriteAnimation(name string, anim sprite.Animation) (*resource.Animation, error)

FromSpriteAnimation converts a sprite.Animation (such as one loaded from an Aseprite tag) into a validated animation clip with one discrete sprite.frame track matching its frames, exact durations and loop flag. Frame events, when present, become clip events at their frame's start time.

func KeyValue

func KeyValue(v float32) float64

KeyValue widens a key's float32 value or time to float64 by its shortest decimal form, so a key written 0.1 plays as 0.1 rather than 0.10000000149011612.

func NoopBinder

func NoopBinder(_ string, _ Property) (func(float64), error)

NoopBinder is a Binder that accepts every track without mutating any scene, for headless state machine verification.

func ScreenAnimations

func ScreenAnimations(clips ClipResolver) func(screen *gameui.BuiltScreen, name, path string) (gameui.ScreenClip, error)

ScreenAnimations returns a loader callback for gameui.ScreenBuildOptions.Animations that resolves *.animation.yaml clips from clips (such as a *resource.Library or animclip.ClipMap) and binds them to the screen with ScreenProperties and BindScreen.

func Seconds

func Seconds(s float32) time.Duration

Seconds converts a clip time in seconds, as keys and events store it, to a time.Duration through KeyValue, so a key at 0.1 sits at exactly 100ms. Values beyond what a Duration holds saturate.

func ValidateStateMachine

func ValidateStateMachine(doc *StateMachineDoc) error

ValidateStateMachine checks doc's version, header, parameters, states, entry state and every transition's endpoints and condition expression.

Types

type Binder

type Binder func(target string, p Property) (set func(v float64), err error)

Binder connects a clip track to what it drives: given the track's target and resolved property, it returns the function that writes the property's value. The value it receives is already converted for the property's kind and range (Property.Convert). An error fails NewPlayer, so a clip that names a missing object is refused before it plays.

func BindDoc

func BindDoc(doc *sceneformat.SceneDoc, self string) Binder

BindDoc returns a Binder that writes into the objects of doc. A track's target is an object ID anywhere in the scene, and an empty target is self, the object the clip plays on. Binding fails for an object the scene does not have, or for a sprite.frame track on an object without a sprite.

func BindScene

func BindScene(scene *sceneformat.BuiltScene, self string) Binder

BindScene returns a Binder that writes into the objects of a built scene, as BindDoc does, and syncs each object whose field it writes (sceneformat.BuiltObject.Sync), so the next Draw shows the object and its children at their new world transform, sprite frame and alpha, alpha multiplied by the material's opacity as Build does. For a sprite.frame track, binding checks that the object has a sprite and that its atlas holds every keyed frame name.

func BindScreen

func BindScreen(screen *gameui.BuiltScreen) Binder

BindScreen returns a Binder that drives nodes in screen by node ID. Every track must name a canvas node ID present in screen and a property from ScreenProperties.

type Blend2DDoc

type Blend2DDoc struct {
	X       string           `yaml:"x"`
	Y       string           `yaml:"y"`
	Mode    string           `yaml:"mode,omitempty"`
	Samples []BlendSampleDoc `yaml:"samples"`
}

Blend2DDoc selects a clip sample from a two-dimensional parameter vector.

type BlendSampleDoc

type BlendSampleDoc struct {
	X    float32 `yaml:"x"`
	Y    float32 `yaml:"y"`
	Clip string  `yaml:"clip"`
}

BlendSampleDoc places one clip at the point (X, Y) of a Blend2DDoc's parameter space.

type ClipMap

type ClipMap map[string]*resource.Animation

ClipMap is an in-memory ClipResolver keyed by clip path or name, handy for tests and generated clips.

func (ClipMap) Animation

func (m ClipMap) Animation(path string) (*resource.Animation, error)

Animation returns the clip registered under path or an error when absent.

type ClipResolver

type ClipResolver interface {
	Animation(path string) (*resource.Animation, error)
}

ClipResolver loads an animation clip by the path or key written in a StateDoc.Clip field. *resource.Library implements ClipResolver.

type Condition

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

Condition is a compiled boolean transition expression over named state machine parameters.

func CompileCondition

func CompileCondition(expr string, params map[string]ParamType) (*Condition, error)

CompileCondition parses and type-checks expr against params (mapping parameter name to ParamType). Supported syntax:

  • Logical: || (or), && (and), ! (not), ( ... )
  • Comparisons: ==, !=, <, <=, >, >= (and Unicode ≤, ≥)
  • Numeric atoms: float literals, float parameter names, |param|, abs(expr), unary -
  • Boolean atoms: true, false, bool/trigger parameter names, bool == true/false

func (*Condition) Eval

func (c *Condition) Eval(getFloat func(string) float64, getBool func(string) bool) bool

Eval evaluates c against the given float and bool/trigger parameter lookup functions.

func (*Condition) Params

func (c *Condition) Params() []string

Params returns the sorted unique parameter names referenced by c.

type FSClips

type FSClips struct {
	FS fs.FS
}

FSClips resolves animation clip YAML files from an fs.FS relative to its root.

func (FSClips) Animation

func (r FSClips) Animation(path string) (*resource.Animation, error)

Animation reads and parses the animation resource at path from FS.

type FSSounds

type FSSounds struct{ FS fs.FS }

FSSounds is a SoundResolver that reads and parses sound resources from an fs.FS.

func (FSSounds) Sound

func (r FSSounds) Sound(path string) (*resource.Sound, error)

Sound reads and parses the sound resource at path from FS.

type FSStates

type FSStates struct {
	FS fs.FS
}

FSStates resolves *.states.yaml files from an fs.FS relative to its root.

func (FSStates) StateMachine

func (r FSStates) StateMachine(path string) (*StateMachineDoc, error)

StateMachine reads and parses the *.states.yaml file at path from FS.

type InputDriver

type InputDriver struct {
	// JumpVelocity is the initial upward velocity (negative Y) applied when jumping on the floor. Defaults to -260 when 0.
	JumpVelocity float64
	// Gravity is the downward acceleration (positive Y) applied while airborne. Defaults to 780 when 0.
	Gravity float64

	// PosY is the simulated vertical offset relative to the floor (0 = on floor, < 0 = airborne).
	PosY float64
	// VelY is the simulated vertical velocity (> 0 = falling).
	VelY float64
	// OnFloor reports whether the simulated character is standing on the floor.
	OnFloor bool

	// MoveX is the most recent horizontal movement input in [-1, 1].
	MoveX float64
}

InputDriver translates 2D character input actions (move_left/move_right or move_x axis, jump, attack, hurt) and simple vertical jump physics into standard state machine parameters (move.x, velocity.y, on_floor, jump, attack, hurt) on every fixed step. Both the editor's "Drive with keys" preview and scripted input tests use InputDriver so behavior is identical.

func NewInputDriver

func NewInputDriver() *InputDriver

NewInputDriver returns an InputDriver standing on the floor with default platformer jump/gravity parameters.

func (*InputDriver) Reset

func (d *InputDriver) Reset()

Reset puts the simulated character back on the floor with zero velocity.

func (*InputDriver) StepActions

func (d *InputDriver) StepActions(sm *StateMachine, actions *input.Actions, dt time.Duration)

StepActions reads actions (stepped by the caller via actions.Step()), advances jump/fall vertical physics by dt, and feeds move.x, velocity.y, on_floor, jump, attack and hurt into sm.

func (*InputDriver) StepSignals

func (d *InputDriver) StepSignals(sm *StateMachine, moveX float64, jumpPressed, attackPressed, hurtPressed bool, dt time.Duration)

StepSignals advances jump/fall physics by dt from direct control signals and feeds parameters into sm.

type Kind

type Kind uint8

Kind is how a keyed value is written to its property.

const (
	// KindFloat writes the number as it is, clamped to the property's range.
	KindFloat Kind = iota + 1
	// KindInt rounds the number to the nearest whole number (halves away from zero), clamped to the property's range.
	KindInt
	// KindBool writes true from 0.5 up and false below it; its keys must be 0 or 1.
	KindBool
	// KindFrame writes a discrete atlas frame name onto the object's sprite without interpolation.
	KindFrame
	// KindColor writes an interpolated RGBA color onto an object's tint or a registered FieldColor component field.
	KindColor
)

func (Kind) String

func (k Kind) String() string

String returns the kind's name: "float", "int", "bool", "frame" or "color".

type ParamDoc

type ParamDoc struct {
	// Name is the parameter identifier used in transition expressions, such as "move.x", "velocity.y", "on_floor" or "jump".
	Name string `yaml:"name" schema:"required"`
	// Type is the parameter kind: "float", "bool" or "trigger".
	Type ParamType `yaml:"type" schema:"required,enum=float|bool|trigger"`
	// Default is the optional starting value: a number for "float", a boolean for "bool", and omitted for "trigger".
	Default any `yaml:"default,omitempty"`
}

ParamDoc declares one named parameter of a StateMachineDoc.

type ParamType

type ParamType string

ParamType is the value kind of a state machine parameter.

const (
	// ParamFloat holds a finite float64 value (default 0).
	ParamFloat ParamType = "float"
	// ParamBool holds a boolean value (default false).
	ParamBool ParamType = "bool"
	// ParamTrigger is a one-shot boolean pulse set via Trigger and cleared at the end of Update.
	ParamTrigger ParamType = "trigger"
)

type Player

type Player struct {
	// OnEvent, when set, is called with the name of each clip event playback crosses, in playback order. Seek does not call it.
	OnEvent func(name string)
	// OnEventArgs, when set, is called with the name and a shallow copy of the arguments map (nil when the event has no arguments) of each clip event playback crosses, in playback order. Seek does not call it.
	OnEventArgs func(name string, args map[string]any)
	// OnSound, when set, is called with the sound resource path of each sound key playback crosses, in playback order. Seek does not call it.
	OnSound func(path string)
	// contains filtered or unexported fields
}

Player plays one animation clip on a tween.Timeline: Play, Pause and Update run it on game.Loop's fixed steps, Seek scrubs it, and the clip's Loop wraps it. It writes nothing until the first Seek or Update.

The player reads the clip once in NewPlayer; to play an edited or reloaded clip, make a new Player.

func NewPlayer

func NewPlayer(clip *resource.Animation, reg *sceneformat.ComponentRegistry, bind Binder) (*Player, error)

NewPlayer checks clip against reg (Check), binds every track through bind, and returns a player at time 0. Each pair of neighboring keys becomes one tween from the first key's value to the second's, eased by the first key's interp; a track's value holds its first key before it and its last key after it, as resource.Animation.Sample does.

func NewPlayerProps

func NewPlayerProps(clip *resource.Animation, props []Property, bind Binder) (*Player, error)

NewPlayerProps checks clip against an explicit property set (such as ScreenProperties), binds every track through bind, and returns a player at time 0.

func (*Player) ClearQueue

func (p *Player) ClearQueue()

ClearQueue removes all pending queued clips without interrupting the currently playing clip.

func (*Player) Clip

func (p *Player) Clip() *resource.Animation

Clip returns the clip currently active on the player.

func (*Player) Close

func (p *Player) Close()

Close releases what the player holds outside itself: the sound effects it loaded through its Mixer for sound keys, and the nested clips it started. Sounds still playing stop as their effects close. Call it when the player is no longer used, such as before replacing it with a new Player; the player can still Seek afterwards, and a later sound key loads its sound again.

func (*Player) Done

func (p *Player) Done() bool

Done reports whether a clip that does not loop has played to its end, no queued clips remain, and every nested clip it started that does not loop has finished too. A looping nested clip does not hold Done back.

func (*Player) Length

func (p *Player) Length() time.Duration

Length returns the active clip's length.

func (*Player) Loop

func (p *Player) Loop() bool

Loop reports whether playback wraps to the start at the end: the clip's Loop unless SetLoop changed it.

func (*Player) Pause

func (p *Player) Pause()

Pause stops playback at the current position.

func (*Player) Play

func (p *Player) Play()

Play starts or resumes playback from the current position. If the current clip is finished and a queued clip is waiting, Play advances to the queued clip. Otherwise a clip that has played to its end stays there; use Restart.

func (*Player) Playing

func (p *Player) Playing() bool

Playing reports whether the player is playing.

func (*Player) Queue

func (p *Player) Queue(clip *resource.Animation) error

Queue validates and binds clip with the player's property set and binder, then appends it to the FIFO playback queue. When the current non-looping clip finishes, the player automatically starts the next queued clip, carrying forward callbacks, speed, mixer and nested clip configuration.

func (*Player) QueueLen

func (p *Player) QueueLen() int

QueueLen returns the number of clips queued to play after the active clip.

func (*Player) Restart

func (p *Player) Restart()

Restart writes the clip's start (0 when speed >= 0, Length when speed < 0) and plays from it.

func (*Player) Seek

func (p *Player) Seek(at time.Duration)

Seek moves to at and writes every track's value there without calling OnEvent, OnEventArgs, OnSound, or starting nested clips. A looping clip wraps a time before 0 or past Length into [0, Length), and poses its end at exactly Length, so a playhead dragged to the end shows the last keys; one that does not loop clamps at to [0, Length].

func (*Player) SetLoop

func (p *Player) SetLoop(loop bool)

SetLoop overrides the active clip's Loop for this player.

func (*Player) SetOnEvent

func (p *Player) SetOnEvent(fn func(name string))

SetOnEvent sets the event callback invoked when playback crosses a clip event.

func (*Player) SetOnEventArgs

func (p *Player) SetOnEventArgs(fn func(name string, args map[string]any))

SetOnEventArgs sets the callback invoked with the event name and argument map when playback crosses a clip event.

func (*Player) SetSpeed

func (p *Player) SetSpeed(speed float64)

SetSpeed sets the playback speed multiplier. Negative values play backwards (crossing events in reverse order), 0 freezes playback without pausing, and NaN or infinite values are ignored.

func (*Player) Speed

func (p *Player) Speed() float64

Speed returns the playback speed multiplier; negative values play backwards and 0 freezes advancement.

func (*Player) Time

func (p *Player) Time() time.Duration

Time returns the playback position, from 0 to Length.

func (*Player) Update

func (p *Player) Update(dt time.Duration)

Update advances a playing clip by dt (scaled by Speed), writes every track's value at the new position, fires events, sounds and nested clip keys crossed during the step, and advances to queued clips as non-looping clips finish.

func (*Player) WithAudioSource

func (p *Player) WithAudioSource(fn func(path string) audio.Source) *Player

WithAudioSource configures a mapper from variant audio file paths to audio.Source values when playing sound keys through a Mixer. It returns p for chaining.

func (*Player) WithClipPath

func (p *Player) WithClipPath(path string) *Player

WithClipPath records the project-relative path of the root clip so runtime nested clip playback can refuse direct self-cycles even when CheckClips was not called beforehand. It returns p for chaining.

func (*Player) WithClips

func (p *Player) WithClips(clips ClipResolver) *Player

WithClips attaches a ClipResolver used to load and play nested clip keys on target objects during Update. It returns p for chaining.

func (*Player) WithMixer

func (p *Player) WithMixer(m *sound.Mixer) *Player

WithMixer attaches a sound.Mixer used to play clip sound keys during Update (never during Seek). It returns p for chaining.

func (*Player) WithSoundFS

func (p *Player) WithSoundFS(fsys fs.FS) *Player

WithSoundFS configures the file system used to read *.sound.yaml resources and audio variant files for clip sound keys. It returns p for chaining.

func (*Player) WithSoundResolver

func (p *Player) WithSoundResolver(r SoundResolver) *Player

WithSoundResolver configures a SoundResolver used to load *.sound.yaml resources for clip sound keys. It returns p for chaining.

type Property

type Property struct {
	// Name is the property as a track writes it: an object field such as "x" or "sprite.frame", or "component.field" for a registered component field.
	Name string
	// Component and Field name the registered component field the property is; both are empty for an object field.
	Component, Field string
	// Kind is how a keyed value is written to the property.
	Kind Kind
	// Min and Max are the property's optional inclusive bounds; nil leaves that side open.
	Min, Max *float64
	// Doc is a one-line description for tools such as the editor.
	Doc string
	// Frames lists the atlas frame names of a KindFrame track in key order while NewPlayer binds a clip, so a Binder can validate them up front and map each keyed index through Property.Frame. It is nil on properties returned by Lookup or Properties.
	Frames []string
}

Property is one property a clip track can key.

func Lookup

func Lookup(reg *sceneformat.ComponentRegistry, name string) (Property, error)

Lookup resolves the property name a track writes. Built-in object properties (including "sprite.frame") resolve without a registry; any other "component.field" is a field of a component registered in reg, split at the first dot. It fails for an unknown object field, a component property without a registry, an unregistered component or field, and a string component field.

func LookupProp

func LookupProp(props []Property, name string) (Property, error)

LookupProp resolves name from an explicit property slice such as ScreenProperties.

func ObjectProperties

func ObjectProperties() []Property

ObjectProperties returns the object fields a clip can key, in the order tools list them.

func Properties

func Properties(reg *sceneformat.ComponentRegistry) []Property

Properties returns every property a clip can key with reg: the object fields, then each registered component's numeric and bool fields, components by name and fields in declaration order. A nil reg returns the object fields only.

func ScreenProperties

func ScreenProperties() []Property

ScreenProperties returns the gameui screen node properties an animation clip can key: x, y, scaleX, scaleY, rotation, alpha, and visible.

func (Property) CheckColor

func (p Property) CheckColor(color string) error

CheckColor reports why color cannot be a key of a KindColor property.

func (Property) CheckFrame

func (p Property) CheckFrame(frame string) error

CheckFrame reports why frame cannot be a key of a KindFrame property.

func (Property) CheckValue

func (p Property) CheckValue(v float64) error

CheckValue reports why v cannot be a key of the property: it is not finite, a frame or color property keyed with a number, a bool key other than 0 or 1, a fractional int key or one a Go int cannot hold, or outside the range.

func (Property) Color

func (p Property) Color(v float64) core.Color

Color unpacks a float64 value delivered by NewPlayer on a KindColor track back to its core.Color, or 0 when p is not KindColor or v is NaN.

func (Property) Convert

func (p Property) Convert(v float64) float64

Convert returns v as the property takes it: rounded for KindInt, 0 or 1 for KindBool, clamped index for KindFrame, and clamped to the range. NaN is returned unchanged.

func (Property) Frame

func (p Property) Frame(v float64) string

Frame maps a keyed index value from NewPlayer to its frame name in p.Frames, or "" when p is not a KindFrame track or v is out of range.

func (Property) Get

Get returns the property's value on o as a number: an object field's value (1 for an unset scale or alpha), or a component field's value with reg's default when o leaves it unset. A bool reads as 0 or 1.

func (Property) GetColor

GetColor returns the CSS color string on o for a KindColor property (object tint or a registered FieldColor component field).

func (Property) GetFrame

func (p Property) GetFrame(o *sceneformat.ObjectDoc) (string, error)

GetFrame returns the sprite frame name on o for a KindFrame property.

func (Property) IsColor

func (p Property) IsColor() bool

IsColor reports whether the property keys RGBA colors rather than numbers or frames.

func (Property) IsComponent

func (p Property) IsComponent() bool

IsComponent reports whether the property is a registered component field rather than an object field.

func (Property) IsFrame

func (p Property) IsFrame() bool

IsFrame reports whether the property keys discrete atlas frame names rather than numbers.

func (Property) Set

func (p Property) Set(o *sceneformat.ObjectDoc, v float64)

Set writes v to the property on o after Convert: a float32 object field, a bool flip, or a component field stored as float64, int or bool, creating the component's mapping when o has none. A NaN v writes nothing.

func (Property) SetColor

func (p Property) SetColor(o *sceneformat.ObjectDoc, c core.Color)

SetColor writes c onto o's tint or FieldColor component field when p is a KindColor property.

func (Property) SetFrame

func (p Property) SetFrame(o *sceneformat.ObjectDoc, frame string)

SetFrame writes frame onto o's sprite when p is a KindFrame property and o has a sprite.

type ScriptStep

type ScriptStep struct {
	// At is when this step starts, relative to simulation start (0).
	At time.Duration `json:"at"`
	// Duration is how long held inputs (MoveX) stay active; 0 means a single-step pulse.
	Duration time.Duration `json:"duration,omitempty"`
	// MoveX holds horizontal movement input in [-1, 1] for Duration.
	MoveX float64 `json:"moveX,omitempty"`
	// Jump pulses the jump input on the first step of this segment.
	Jump bool `json:"jump,omitempty"`
	// Attack pulses the attack input on the first step of this segment.
	Attack bool `json:"attack,omitempty"`
	// Hurt pulses the hurt input on the first step of this segment.
	Hurt bool `json:"hurt,omitempty"`
	// Floats optionally sets arbitrary named float parameters for Duration.
	Floats map[string]float64 `json:"floats,omitempty"`
	// Bools optionally sets arbitrary named bool parameters for Duration.
	Bools map[string]bool `json:"bools,omitempty"`
	// Triggers optionally pulses arbitrary named trigger parameters at At.
	Triggers []string `json:"triggers,omitempty"`
}

ScriptStep describes one timed input segment in a scripted simulation of a sprite state machine.

func DefaultScript

func DefaultScript() []ScriptStep

DefaultScript returns an 8-second scripted input sequence exercising idle, run, jump, fall, landing back into run, idle, attack and hurt.

type SimulationOptions

type SimulationOptions struct {
	// Duration is total simulated time; defaults to 8 seconds when <= 0.
	Duration time.Duration
	// Rate is fixed steps per second; defaults to 60 when <= 0.
	Rate int
	// Script are the timed inputs played during simulation; when empty, DefaultScript(Duration) is used.
	Script []ScriptStep
	// Driver optionally supplies a custom InputDriver; nil uses NewInputDriver().
	Driver *InputDriver
}

SimulationOptions configures SimulateStateMachine.

type SimulationReport

type SimulationReport struct {
	// Duration is the total simulated duration.
	Duration time.Duration `json:"duration"`
	// Steps is the number of fixed steps executed.
	Steps int `json:"steps"`
	// Trace is the ordered sequence of states visited (entry state first, then each transition target).
	Trace []string `json:"trace"`
	// Transitions lists every state change in chronological order.
	Transitions []TransitionEvent `json:"transitions"`
	// VisitedStates are the sorted unique state names entered during the run.
	VisitedStates []string `json:"visitedStates"`
	// UnvisitedStates are the sorted state names declared in the document that were never entered.
	UnvisitedStates []string `json:"unvisitedStates,omitempty"`
	// StuckStates are the sorted state names that finished a non-looping clip and remained stuck without leaving, or have no outgoing transitions at all.
	StuckStates []string `json:"stuckStates,omitempty"`
}

SimulationReport summarizes a scripted simulation run of a StateMachineDoc.

func SimulateStateMachine

func SimulateStateMachine(doc *StateMachineDoc, clips ClipResolver, reg *sceneformat.ComponentRegistry, bind Binder, opts SimulationOptions) (*SimulationReport, error)

SimulateStateMachine runs doc deterministically under opts.Script for opts.Duration at opts.Rate Hz and returns a SimulationReport detailing the visited state trace, transitions and any stuck states. If bind is nil, NoopBinder is used.

func (*SimulationReport) Summary

func (r *SimulationReport) Summary() string

Summary formats a concise one-line status, e.g. "Played 8 s of scripted input · no stuck states".

type SoundMap

type SoundMap map[string]*resource.Sound

SoundMap is an in-memory SoundResolver keyed by project-relative sound resource path.

func (SoundMap) Sound

func (m SoundMap) Sound(path string) (*resource.Sound, error)

Sound returns the sound registered under path or an error when absent.

type SoundResolver

type SoundResolver interface {
	Sound(path string) (*resource.Sound, error)
}

SoundResolver loads a sound resource file (such as "sounds/sword.sound.yaml") by its slash-separated project-relative path.

type StateDoc

type StateDoc struct {
	// Name is the unique state name within the state machine, such as "idle" or "run".
	Name string `yaml:"name" schema:"required"`
	// Clip is the project-relative path or resolver key of the animation clip resource played while this state is active.
	Clip string `yaml:"clip,omitempty"`
	// Blend2D optionally makes this state a 2D blend space that picks among clip samples by two float parameters, instead of playing Clip. A state chooses exactly one of clip, blend2d or states.
	Blend2D *Blend2DDoc `yaml:"blend2d,omitempty"`
	// Nested optionally names a nested state machine resource this state runs, instead of playing Clip. A state chooses exactly one of clip, blend2d or states. Metadata only until nested-machine playback lands.
	Nested string `yaml:"states,omitempty"`
	// Speed is an optional playback speed multiplier (> 0); 0 or omitted plays at 1x speed.
	Speed float32 `yaml:"speed,omitempty" schema:"minimum=0"`
	// Loop optionally overrides the clip's own loop setting while played in this state.
	Loop *bool `yaml:"loop,omitempty"`
	// X is an optional horizontal coordinate of this state node in the editor graph.
	X *float32 `yaml:"x,omitempty"`
	// Y is an optional vertical coordinate of this state node in the editor graph.
	Y *float32 `yaml:"y,omitempty"`
}

StateDoc declares one state of a StateMachineDoc.

type StateMachine

type StateMachine struct {
	// OnTransition, when set, is called synchronously whenever the machine switches states.
	OnTransition func(from, to string)
	// OnEvent, when set, is called synchronously whenever the active state's clip crosses a named cue event.
	OnEvent func(state, event string)
	// contains filtered or unexported fields
}

StateMachine plays a *.states.yaml sprite animation graph on deterministic game.Loop fixed steps. The game (or editor preview) sets named float, bool and trigger parameters and calls Update(dt).

func NewAnimator

func NewAnimator(built *sceneformat.BuiltScene, objectID string, states StatesResolver, clips ClipResolver, reg *sceneformat.ComponentRegistry) (*StateMachine, error)

NewAnimator builds a StateMachine for objectID in built from its built-in "animator" component, resolving the states file via states and each state's clip via clips.

func NewStateMachine

func NewStateMachine(doc *StateMachineDoc, clips ClipResolver, reg *sceneformat.ComponentRegistry, bind Binder) (*StateMachine, error)

NewStateMachine validates doc, resolves every state's clip through clips, builds a Player for each state bound via bind, and starts at doc.Entry (playing and posed at time 0). It refuses a document with a blend2d or nested state, which it cannot play yet.

func (*StateMachine) ActivePlayer

func (sm *StateMachine) ActivePlayer() *Player

ActivePlayer returns the clip Player of the currently active state, or nil.

func (*StateMachine) Bool

func (sm *StateMachine) Bool(name string) bool

Bool returns the current value of bool or trigger parameter name.

func (*StateMachine) Doc

func (sm *StateMachine) Doc() *StateMachineDoc

Doc returns a copy of the StateMachineDoc this player runs.

func (*StateMachine) Float

func (sm *StateMachine) Float(name string) float64

Float returns the current value of float parameter name, or 0 when unset.

func (*StateMachine) Params

func (sm *StateMachine) Params() map[string]any

Params returns a snapshot map of all declared parameters and their current values.

func (*StateMachine) Pause

func (sm *StateMachine) Pause()

Pause halts playback at the current state and time.

func (*StateMachine) Play

func (sm *StateMachine) Play()

Play resumes fixed-step playback.

func (*StateMachine) Playing

func (sm *StateMachine) Playing() bool

Playing reports whether playback advances on Update.

func (*StateMachine) PreviousState

func (sm *StateMachine) PreviousState() string

PreviousState returns the name of the state active before the last transition, or "" before any transition has fired.

func (*StateMachine) Reset

func (sm *StateMachine) Reset()

Reset restores all parameters to their defaults, clears triggers, re-enters doc.Entry and poses frame 0.

func (*StateMachine) ResetTrigger

func (sm *StateMachine) ResetTrigger(name string)

ResetTrigger clears a latched trigger parameter before Update consumes it.

func (*StateMachine) SetBool

func (sm *StateMachine) SetBool(name string, v bool)

SetBool sets a declared bool parameter to v. Unknown/non-bool names are ignored.

func (*StateMachine) SetFloat

func (sm *StateMachine) SetFloat(name string, v float64)

SetFloat sets a declared float parameter to v. Non-finite values and unknown/non-float names are ignored.

func (*StateMachine) SetSpeed

func (sm *StateMachine) SetSpeed(speed float64)

SetSpeed sets the global playback speed multiplier (>= 0).

func (*StateMachine) SetState

func (sm *StateMachine) SetState(name string) bool

SetState switches immediately to state name, restarting its clip from time 0 and posing frame 0. When switching to a different state, OnTransition and any connected "animator.stateChanged" signal fire. Returns false when name is not a state in the machine.

func (*StateMachine) Speed

func (sm *StateMachine) Speed() float64

Speed returns the global playback speed multiplier.

func (*StateMachine) State

func (sm *StateMachine) State() string

State returns the name of the currently active state.

func (*StateMachine) StateDone

func (sm *StateMachine) StateDone() bool

StateDone reports whether the active non-looping clip has played to its end.

func (*StateMachine) StateLength

func (sm *StateMachine) StateLength() time.Duration

StateLength returns the active clip's total length.

func (*StateMachine) StateTime

func (sm *StateMachine) StateTime() time.Duration

StateTime returns the active clip's current playback time.

func (*StateMachine) Trigger

func (sm *StateMachine) Trigger(name string)

Trigger pulses a declared trigger parameter for the next Update step.

func (*StateMachine) Update

func (sm *StateMachine) Update(dt time.Duration)

Update advances the state machine by one fixed step dt: evaluates transitions in declaration order, advances the active clip player (firing clip events), checks clip-end transitions if the clip finished on this step, and resets all trigger pulses at the end of the step.

type StateMachineDoc

type StateMachineDoc struct {
	// Version is the schema version; it must equal StateMachineVersion (1).
	Version int `yaml:"version" schema:"required"`
	// UID is an optional stable file ID assigned by game index or the editor for safe renames.
	UID string `yaml:"uid,omitempty"`
	// Name is an optional human-readable display name for the state machine.
	Name string `yaml:"name,omitempty"`
	// Entry is the name of the state the machine enters when playback starts or resets.
	Entry string `yaml:"entry" schema:"required"`
	// Parameters are the named inputs that transition conditions read.
	Parameters []ParamDoc `yaml:"parameters,omitempty"`
	// States are the named animation states, each playing one animation clip.
	States []StateDoc `yaml:"states" schema:"required"`
	// Transitions are the directed edges evaluated in declaration order on every fixed Update step.
	Transitions []TransitionDoc `yaml:"transitions,omitempty"`
}

StateMachineDoc is the plain-text YAML schema of a *.states.yaml sprite animation state machine.

func ParseStateMachine

func ParseStateMachine(data []byte) (*StateMachineDoc, error)

ParseStateMachine decodes data as a *.states.yaml document, refusing unknown fields, trailing documents, unsupported versions and invalid states, parameters or transition expressions.

Errors are *loaderr.Error values with line, field and fix; validation errors keep *StateMachineError in the chain.

func (*StateMachineDoc) Clone

func (doc *StateMachineDoc) Clone() *StateMachineDoc

Clone returns a deep copy of doc.

func (*StateMachineDoc) State

func (doc *StateMachineDoc) State(name string) *StateDoc

State returns a pointer to the named state in doc, or nil when absent.

func (*StateMachineDoc) UnusedParameters

func (doc *StateMachineDoc) UnusedParameters() []int

UnusedParameters returns the indices into doc.Parameters of parameters that no transition condition reads.

func (*StateMachineDoc) UsedParameters

func (doc *StateMachineDoc) UsedParameters() map[string]bool

UsedParameters returns the set of parameter names referenced by at least one transition's When condition.

type StateMachineError

type StateMachineError struct {
	// Path is the sequence of YAML mapping keys and decimal slice indices leading to the offending field, such as ["transitions", "2", "to"].
	Path []string
	// Message describes what is wrong and how to fix it.
	Message string
}

StateMachineError reports a validation error in a StateMachineDoc together with the YAML field path that caused it, so callers such as assetcheck can locate the exact line.

func (*StateMachineError) Error

func (e *StateMachineError) Error() string

Error implements error.

type StatesMap

type StatesMap map[string]*StateMachineDoc

StatesMap is an in-memory StatesResolver keyed by path.

func (StatesMap) StateMachine

func (m StatesMap) StateMachine(path string) (*StateMachineDoc, error)

StateMachine returns the document registered under path or an error when absent.

type StatesResolver

type StatesResolver interface {
	StateMachine(path string) (*StateMachineDoc, error)
}

StatesResolver loads a *.states.yaml StateMachineDoc by its project-relative path.

type TransitionDoc

type TransitionDoc struct {
	// From is the source state name, or "*" (AnyState) to match any state other than To.
	From string `yaml:"from" schema:"required"`
	// To is the target state name; it must name a state in States.
	To string `yaml:"to" schema:"required"`
	// Label is an optional human-readable summary shown on the editor graph edge and LEAVING list.
	Label string `yaml:"label,omitempty"`
	// When is an optional boolean expression over declared parameters, such as "|move.x| > 0.1" or "jump && on_floor".
	When string `yaml:"when,omitempty"`
	// OnEnd fires this transition when the source state's clip finishes playing (and When, if set, is also true).
	OnEnd bool `yaml:"onEnd,omitempty"`
	// Switch selects when the transition takes effect: "immediate", "sync" or "atEnd" (which, like OnEnd, waits for the source clip to finish); empty means immediate. Metadata only until runtime crossfade lands.
	Switch string `yaml:"switch,omitempty" schema:"enum=immediate|sync|atEnd"`
	// XFade is the crossfade length into the target state; must be finite and non-negative. Metadata only until runtime crossfade lands.
	XFade float32 `yaml:"xfade,omitempty" schema:"minimum=0"`
	// Priority orders transitions that could fire at the same time. Metadata only until runtime travel playback lands.
	Priority int `yaml:"priority,omitempty"`
}

TransitionDoc declares one directed transition from From (or "*" for any state) to To.

type TransitionEvent

type TransitionEvent struct {
	// Time is the simulation time when the transition fired.
	Time time.Duration `json:"time"`
	// From is the state left.
	From string `json:"from"`
	// To is the state entered.
	To string `json:"to"`
}

TransitionEvent records one state change observed during scripted simulation.

Jump to

Keyboard shortcuts

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