API リファレンスはソースコード内の Go ドキュメントコメントから生成されており、英語で記述されています。
package animclip
import "github.com/nsgo-dev/game/pkg/animclip"概要
Package animclip plays animation clips, the resource files of type animation that key any registered property of scene objects on a timeline, as Godot's AnimationPlayer does.
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.
目次
- 定数
- func Check(clip *resource.Animation, reg *sceneformat.ComponentRegistry) error
- func EncodeStateMachine(doc *StateMachineDoc) ([]byte, error)
- func FromAsepriteTag(atlas *sprite.Atlas, tag string) (*resource.Animation, error)
- func FromFrames(name string, frames []string, fps float64, loop bool) (*resource.Animation, error)
- func FromSpriteAnimation(name string, anim sprite.Animation) (*resource.Animation, error)
- func KeyValue(v float32) float64
- func NoopBinder(_ string, _ Property) (func(float64), error)
- func Seconds(s float32) time.Duration
- func ValidateStateMachine(doc *StateMachineDoc) error
- type Binder
- type ClipMap
- type ClipResolver
- type Condition
- type FSClips
- type FSStates
- type InputDriver
- type Kind
- type ParamDoc
- type ParamType
- type Player
- func NewPlayer(clip *resource.Animation, reg *sceneformat.ComponentRegistry, bind Binder) (*Player, error)
- func (p *Player) Clip() *resource.Animation
- func (p *Player) Done() bool
- func (p *Player) Length() time.Duration
- func (p *Player) Loop() bool
- func (p *Player) Pause()
- func (p *Player) Play()
- func (p *Player) Playing() bool
- func (p *Player) Restart()
- func (p *Player) Seek(at time.Duration)
- func (p *Player) SetLoop(loop bool)
- func (p *Player) Time() time.Duration
- func (p *Player) Update(dt time.Duration)
- type Property
- func Lookup(reg *sceneformat.ComponentRegistry, name string) (Property, error)
- func ObjectProperties() []Property
- func Properties(reg *sceneformat.ComponentRegistry) []Property
- func (p Property) CheckFrame(frame string) error
- func (p Property) CheckValue(v float64) error
- func (p Property) Convert(v float64) float64
- func (p Property) Frame(v float64) string
- func (p Property) Get(o *sceneformat.ObjectDoc, reg *sceneformat.ComponentRegistry) (float64, error)
- func (p Property) GetFrame(o *sceneformat.ObjectDoc) (string, error)
- func (p Property) IsComponent() bool
- func (p Property) IsFrame() bool
- func (p Property) Set(o *sceneformat.ObjectDoc, v float64)
- func (p Property) SetFrame(o *sceneformat.ObjectDoc, frame string)
- type ScriptStep
- type SimulationOptions
- type SimulationReport
- type StateDoc
- type StateMachine
- func NewAnimator(built *sceneformat.BuiltScene, objectID string, states StatesResolver, clips ClipResolver, reg *sceneformat.ComponentRegistry) (*StateMachine, error)
- func NewStateMachine(doc *StateMachineDoc, clips ClipResolver, reg *sceneformat.ComponentRegistry, bind Binder) (*StateMachine, error)
- func (sm *StateMachine) ActivePlayer() *Player
- func (sm *StateMachine) Bool(name string) bool
- func (sm *StateMachine) Doc() *StateMachineDoc
- func (sm *StateMachine) Float(name string) float64
- func (sm *StateMachine) Params() map[string]any
- func (sm *StateMachine) Pause()
- func (sm *StateMachine) Play()
- func (sm *StateMachine) Playing() bool
- func (sm *StateMachine) PreviousState() string
- func (sm *StateMachine) Reset()
- func (sm *StateMachine) ResetTrigger(name string)
- func (sm *StateMachine) SetBool(name string, v bool)
- func (sm *StateMachine) SetFloat(name string, v float64)
- func (sm *StateMachine) SetSpeed(speed float64)
- func (sm *StateMachine) SetState(name string) bool
- func (sm *StateMachine) Speed() float64
- func (sm *StateMachine) State() string
- func (sm *StateMachine) StateDone() bool
- func (sm *StateMachine) StateLength() time.Duration
- func (sm *StateMachine) StateTime() time.Duration
- func (sm *StateMachine) Trigger(name string)
- func (sm *StateMachine) Update(dt time.Duration)
- type StateMachineDoc
- type StateMachineError
- type StatesMap
- type StatesResolver
- type TransitionDoc
- type TransitionEvent
定数
const AnyState = "*"AnyState is the special TransitionDoc.From value matching any active state other than TransitionDoc.To.
const PropertySpriteFrame = "sprite.frame"PropertySpriteFrame is the discrete object property that steps a sprite's atlas frame name without interpolation.
const StateMachineSchemaComment = "# yaml-language-server: $schema=" + StateMachineSchemaURLStateMachineSchemaComment is the first line EncodeStateMachine writes, pointing YAML language servers at StateMachineSchemaURL.
const StateMachineSchemaURL = "https://game.nsgo.dev/schemas/states.v1.json"StateMachineSchemaURL is where the JSON Schema of version 1 sprite state machine documents is published.
const StateMachineVersion = 1StateMachineVersion is the schema version of *.states.yaml files this package reads and writes.
関数
func Check(clip *resource.Animation, reg *sceneformat.ComponentRegistry) errorCheck 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 EncodeStateMachine(doc *StateMachineDoc) ([]byte, error)EncodeStateMachine validates doc and writes deterministic 2-space YAML preceded by StateMachineSchemaComment.
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(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(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(v float32) float64KeyValue 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(_ string, _ Property) (func(float64), error)NoopBinder is a Binder that accepts every track without mutating any scene, for headless state machine verification.
func Seconds(s float32) time.DurationSeconds 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(doc *StateMachineDoc) errorValidateStateMachine checks doc's version, header, parameters, states, entry state and every transition's endpoints and condition expression.
型
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(doc *sceneformat.SceneDoc, self string) BinderBindDoc 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(scene *sceneformat.BuiltScene, self string) BinderBindScene 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.
type ClipMap map[string]*resource.AnimationClipMap is an in-memory ClipResolver keyed by clip path or name, handy for tests and generated clips.
func (m ClipMap) Animation(path string) (*resource.Animation, error)Animation returns the clip registered under path or an error when absent.
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 struct {
// contains filtered or unexported fields
}Condition is a compiled boolean transition expression over named state machine parameters.
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 (c *Condition) Eval(getFloat func(string) float64, getBool func(string) bool) boolEval evaluates c against the given float and bool/trigger parameter lookup functions.
func (c *Condition) Params() []stringParams returns the sorted unique parameter names referenced by c.
type FSClips struct {
FS fs.FS
}FSClips resolves animation clip YAML files from an fs.FS relative to its root.
func (r FSClips) Animation(path string) (*resource.Animation, error)Animation reads and parses the animation resource at path from FS.
type FSStates struct {
FS fs.FS
}FSStates resolves *.states.yaml files from an fs.FS relative to its root.
func (r FSStates) StateMachine(path string) (*StateMachineDoc, error)StateMachine reads and parses the *.states.yaml file at path from FS.
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() *InputDriverNewInputDriver returns an InputDriver standing on the floor with default platformer jump/gravity parameters.
func (d *InputDriver) Reset()Reset puts the simulated character back on the floor with zero velocity.
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 (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 uint8Kind 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
)func (k Kind) String() stringString returns the kind's name: "float", "int", "bool" or "frame".
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 stringParamType 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 struct {
// OnEvent, when set, is called with the name of each clip event playback crosses, in time order. Seek does not call it.
OnEvent func(name 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(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 (p *Player) Clip() *resource.AnimationClip returns the clip the player was made from.
func (p *Player) Done() boolDone reports whether a clip that does not loop has played to its end.
func (p *Player) Loop() boolLoop reports whether playback wraps to the start at the end: the clip's Loop unless SetLoop changed it.
func (p *Player) Play()Play starts or resumes playback from the current position. A clip that has played to its end stays there; use Restart.
func (p *Player) Playing() boolPlaying reports whether the player is playing.
func (p *Player) Restart()Restart writes the clip's start and plays from it.
func (p *Player) Seek(at time.Duration)Seek moves to at and writes every track's value there without calling OnEvent. 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 (p *Player) SetLoop(loop bool)SetLoop overrides the clip's Loop for this player.
func (p *Player) Time() time.DurationTime returns the playback position, from 0 to Length.
func (p *Player) Update(dt time.Duration)Update advances a playing clip by dt, writes every track's value at the new position and calls OnEvent for each event crossed.
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(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 ObjectProperties() []PropertyObjectProperties returns the object fields a clip can key, in the order tools list them.
func Properties(reg *sceneformat.ComponentRegistry) []PropertyProperties 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 (p Property) CheckFrame(frame string) errorCheckFrame reports why frame cannot be a key of a KindFrame property.
func (p Property) CheckValue(v float64) errorCheckValue reports why v cannot be a key of the property: it is not finite, a frame 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 (p Property) Convert(v float64) float64Convert 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 (p Property) Frame(v float64) stringFrame 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 (p Property) Get(o *sceneformat.ObjectDoc, reg *sceneformat.ComponentRegistry) (float64, error)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 (p Property) GetFrame(o *sceneformat.ObjectDoc) (string, error)GetFrame returns the sprite frame name on o for a KindFrame property.
func (p Property) IsComponent() boolIsComponent reports whether the property is a registered component field rather than an object field.
func (p Property) IsFrame() boolIsFrame reports whether the property keys discrete atlas frame names rather than numbers.
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 (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 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() []ScriptStepDefaultScript returns an 8-second scripted input sequence exercising idle, run, jump, fall, landing back into run, idle, attack and hurt.
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 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(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 (r *SimulationReport) Summary() stringSummary formats a concise one-line status, e.g. "Played 8 s of scripted input · no stuck states".
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" schema:"required"`
// 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 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(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(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).
func (sm *StateMachine) ActivePlayer() *PlayerActivePlayer returns the clip Player of the currently active state, or nil.
func (sm *StateMachine) Bool(name string) boolBool returns the current value of bool or trigger parameter name.
func (sm *StateMachine) Doc() *StateMachineDocDoc returns a copy of the StateMachineDoc this player runs.
func (sm *StateMachine) Float(name string) float64Float returns the current value of float parameter name, or 0 when unset.
func (sm *StateMachine) Params() map[string]anyParams returns a snapshot map of all declared parameters and their current values.
func (sm *StateMachine) Pause()Pause halts playback at the current state and time.
func (sm *StateMachine) Playing() boolPlaying reports whether playback advances on Update.
func (sm *StateMachine) PreviousState() stringPreviousState returns the name of the state active before the last transition, or "" before any transition has fired.
func (sm *StateMachine) Reset()Reset restores all parameters to their defaults, clears triggers, re-enters doc.Entry and poses frame 0.
func (sm *StateMachine) ResetTrigger(name string)ResetTrigger clears a latched trigger parameter before Update consumes it.
func (sm *StateMachine) SetBool(name string, v bool)SetBool sets a declared bool parameter to v. Unknown/non-bool names are ignored.
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 (sm *StateMachine) SetSpeed(speed float64)SetSpeed sets the global playback speed multiplier (>= 0).
func (sm *StateMachine) SetState(name string) boolSetState switches immediately to state name, restarting its clip from time 0 and posing frame 0. Returns false when name is not a state in the machine.
func (sm *StateMachine) Speed() float64Speed returns the global playback speed multiplier.
func (sm *StateMachine) State() stringState returns the name of the currently active state.
func (sm *StateMachine) StateDone() boolStateDone reports whether the active non-looping clip has played to its end.
func (sm *StateMachine) StateLength() time.DurationStateLength returns the active clip's total length.
func (sm *StateMachine) StateTime() time.DurationStateTime returns the active clip's current playback time.
func (sm *StateMachine) Trigger(name string)Trigger pulses a declared trigger parameter for the next Update step.
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 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(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.
func (doc *StateMachineDoc) Clone() *StateMachineDocClone returns a deep copy of doc.
func (doc *StateMachineDoc) State(name string) *StateDocState returns a pointer to the named state in doc, or nil when absent.
func (doc *StateMachineDoc) UnusedParameters() []intUnusedParameters returns the indices into doc.Parameters of parameters that no transition condition reads.
func (doc *StateMachineDoc) UsedParameters() map[string]boolUsedParameters returns the set of parameter names referenced by at least one transition's When condition.
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.
type StatesMap map[string]*StateMachineDocStatesMap is an in-memory StatesResolver keyed by path.
func (m StatesMap) StateMachine(path string) (*StateMachineDoc, error)StateMachine returns the document registered under path or an error when absent.
type StatesResolver interface {
StateMachine(path string) (*StateMachineDoc, error)
}StatesResolver loads a *.states.yaml StateMachineDoc by its project-relative path.
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"`
}TransitionDoc declares one directed transition from From (or "*" for any state) to To.
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.