Documentation
¶
Overview ¶
Package skeletal is experimental: its API and documented formats may change in a minor release; see https://nsgo.games/docs/stability/.
Package skeletal loads, saves and animates 2D skeletal rigs drawn through sprite.Batch.
Format decision ¶
Rigs use an open, versioned YAML format (.skel.yaml, version 1) that Load reads and Encode writes. Choosing an open schema over Spine's export avoids Spine's proprietary runtime license, matches NSGo's screen coordinates directly, and is simple to export from DragonBones, Blender or custom scripts. Like every file a game's author edits, a rig is plain text: one bone, slot, attachment or keyframe per line, so it can be edited by hand and reviewed as a diff. A version-1 rig written as JSON loads too when the JSON is also valid YAML: keys spelled exactly as the schema spells them (matching is case-sensitive) and no `\/` escape, which YAML does not have.
Load is strict: it rejects unknown fields, duplicate keys, trailing documents, unsupported versions and non-finite numbers, as well as every structural error listed on Load.
Coordinates and units ¶
Coordinates match package sprite and core.Drawing: +X points right, +Y points down, and rotations are in radians, clockwise on the screen. Keyframe times and animation durations are written in seconds, at most MaxSeconds, and stored as time.Duration in Go.
Schema (version 1) ¶
A rig file is a YAML mapping with:
- version (int, required): must be 1.
- name (string, optional): rig name.
- bones (sequence): bone hierarchy in bind pose. Each bone has name (required, unique), optional parent (another bone's name), local offset x and y, local rotation in radians, local scaleX and scaleY (default 1), and optional length for tooling. Cycles and missing parents are rejected.
- slots (sequence): draw-ordered list, back to front. Each slot has name (required, unique), bone (required, an existing bone's name), optional attachment (default atlas frame name), and alpha in [0, 1] (default 1).
- skins (mapping): maps skin name (default "default") to a mapping of slot name to an attachment {frame, x, y, rotation, scaleX, scaleY, originX, originY}. scaleX and scaleY default to 1. Slots missing from the active skin fall back to "default". An empty frame hides the slot.
- animations (mapping): maps animation name to {duration, loop, bones, slots}. duration is in seconds (derived from the last keyframe when omitted). Each bone timeline has optional translate [{time, x, y, curve, bezier}], rotate [{time, angle, curve, bezier}] and scale [{time, x, y, curve, bezier}], applied relative to bind pose (translate and rotate add; scale multiplies). Each slot timeline has optional attachment [{time, frame}] and alpha [{time, value, curve, bezier}]. curve is "linear" (default), "stepped", or "bezier" with bezier: [cx1, cy1, cx2, cy2] where cx1, cx2 lie in [0, 1]; bezier is rejected on other curves.
Canonical form ¶
Encode writes one canonical form: keys in schema order, skins, attachments, animations and timelines sorted by name in plain byte order (as sort.Strings sorts them), each bone, slot, attachment and keyframe as a one-line flow mapping, fields equal to their defaults left out, except that keyframes always write their time and values and animations their duration, and numbers in plain decimal notation, never with an exponent. Loading a canonical file and encoding it gives the same bytes back, and loading what Encode wrote gives the same rig. Comments and anchors are not kept.
Sample ¶
version: 1
name: runner
bones:
- {name: root}
- {name: torso, parent: root, y: -18, length: 16}
- {name: head, parent: torso, y: -16, length: 12}
slots:
- {name: torso, bone: torso}
- {name: head, bone: head}
skins:
default:
head: {frame: head, originX: 6, originY: 12}
torso: {frame: torso, originX: 6, originY: 16}
animations:
idle:
duration: 1
loop: true
bones:
torso:
translate:
- {time: 0, x: 0, y: 0, curve: bezier, bezier: [0.25, 0.1, 0.25, 1]}
- {time: 0.5, x: 0, y: -2}
- {time: 1, x: 0, y: 0}
Index ¶
- Constants
- func DeformMesh(m MeshAttachment, bones map[string]BoneTransform, offsets []float32) []float32
- func DeformMeshChecked(m MeshAttachment, bones map[string]BoneTransform, offsets []float32) ([]float32, error)
- func Encode(sd *SkeletonData) ([]byte, error)
- func Schema(opts jsonschema.Options) (*jsonschema.Schema, error)
- type Animation
- type AnimationEvent
- type Attachment
- type AttachmentKeyframe
- type BoneData
- type BoneTimeline
- type BoneTransform
- type CurveType
- type FloatKeyframe
- type MeshAttachment
- type MeshWeight
- type Skeleton
- func (s *Skeleton) Animation() string
- func (s *Skeleton) Blending() bool
- func (s *Skeleton) ClearAttachment(slot string)
- func (s *Skeleton) Crossfade(anim string, duration time.Duration, loop bool) error
- func (s *Skeleton) Data() *SkeletonData
- func (s *Skeleton) Done() bool
- func (s *Skeleton) Draw(d *core.Drawing)
- func (s *Skeleton) Play(anim string, loop bool) error
- func (s *Skeleton) ResetToBindPose()
- func (s *Skeleton) SetAttachment(slot, frame string)
- func (s *Skeleton) SetSkin(name string) error
- func (s *Skeleton) Skin() string
- func (s *Skeleton) Update(dt time.Duration)
- func (s *Skeleton) UpdateWorldTransforms()
- func (s *Skeleton) WorldBone(name string) (BoneTransform, bool)
- type SkeletonData
- type Skin
- type SlotData
- type SlotTimeline
- type Vec2Keyframe
Examples ¶
Constants ¶
const FormatVersion = 1
FormatVersion is the schema version that Load reads and Encode writes.
const MaxSeconds = 1_000_000
MaxSeconds is the longest keyframe time or animation duration, in seconds, that a rig may hold. Within it, a time written in seconds by Encode loads back to the same nanosecond.
const SchemaComment = "# yaml-language-server: $schema=" + SchemaURL
SchemaComment is the first line Encode writes: a YAML comment that points a YAML language server at SchemaURL. Load ignores it like any other comment.
const SchemaURL = "https://nsgo.games/schemas/skeletal.v1.json"
SchemaURL is where the JSON Schema of version 1 skeletal rigs is published. Encode names it in a yaml-language-server comment on a rig's first line, so editors and AI tools validate and complete the file as it is written.
Variables ¶
This section is empty.
Functions ¶
func DeformMesh ¶
func DeformMesh(m MeshAttachment, bones map[string]BoneTransform, offsets []float32) []float32
DeformMesh applies linear blend skinning from local vertex positions and bone transforms. Invalid input returns nil. Call DeformMeshChecked when the caller needs the validation error.
func DeformMeshChecked ¶
func DeformMeshChecked(m MeshAttachment, bones map[string]BoneTransform, offsets []float32) ([]float32, error)
DeformMeshChecked applies linear blend skinning from local vertex positions and bone transforms. It validates the attachment, every referenced bone and optional deform offsets before allocating the output.
func Encode ¶
func Encode(sd *SkeletonData) ([]byte, error)
Encode serializes sd as a version-1 .skel.yaml document, SchemaComment on its first line, and checks that the result loads.
The output is deterministic: keys follow the schema's order, skins, attachments, animations and timelines are sorted by name in byte order, numbers are written in plain decimal notation without an exponent, every bone, slot, attachment and keyframe sits on one line in flow style, and values equal to their defaults are left out, except that keyframes always spell out their time and values and animations their duration. Encoding the result of Load gives the same bytes back for a file already in this form, and loading the result of Encode gives data equal to sd.
Encode reports an error, and writes nothing, when sd would not load: a missing or dangling name, a cycle, an unknown curve, a non-finite number, a time outside [0, MaxSeconds], Bezier control points on a curve that is not CurveBezier, an Animation whose Name differs from its key in Animations, or any other rule Load enforces. It does not modify sd.
func Schema ¶
func Schema(opts jsonschema.Options) (*jsonschema.Schema, error)
Schema returns the draft-07 JSON Schema of version 1 skeletal rigs, the format Load reads and Encode writes, for an editor or AI tool to validate and complete a rig while it is written.
The schema is reflected from the wire document Load decodes, whose fields and defaults the loader and encoder share, so its keys, types and descriptions match the format that is read and written. A rig written as JSON, which Load also accepts when it is valid YAML, validates against the same schema.
Types ¶
type Animation ¶
type Animation struct {
// Name is the animation's key in SkeletonData.Animations.
Name string
// Duration is the length of one pass of the animation.
Duration time.Duration
// Loop is the file's default looping preference for this animation.
Loop bool
// Bones maps bone names to their transform timelines.
Bones map[string]BoneTimeline
// Slots maps slot names to their attachment and alpha timelines.
Slots map[string]SlotTimeline
// Events are the animation's event markers, in non-decreasing Time order.
Events []AnimationEvent
// contains filtered or unexported fields
}
Animation holds the bone and slot timelines for one named motion.
type AnimationEvent ¶
type AnimationEvent struct {
// Time is when the event fires, from 0 to the animation's Duration.
Time time.Duration
// Name is passed to Skeleton.OnEvent; it must not be empty, and several events may share it.
Name string
}
AnimationEvent marks a moment in an animation at which Skeleton.OnEvent is called, such as a footstep or a hit frame.
type Attachment ¶
type Attachment struct {
// Frame is the atlas frame name to draw; empty hides the slot.
Frame string
// X and Y are the attachment's offset in its bone's local space.
X, Y float32
// Rotation is the attachment's local rotation in radians, clockwise on the screen.
Rotation float32
// ScaleX and ScaleY are the attachment's local scales, 1 when omitted in the file.
ScaleX, ScaleY float32
// OriginX and OriginY are the pivot point of the untrimmed atlas frame, matching sprite.Sprite.
OriginX, OriginY float32
}
Attachment places one atlas frame on a slot, relative to the slot's bone.
type AttachmentKeyframe ¶
AttachmentKeyframe swaps a slot's atlas frame at Time; an empty Frame hides the slot.
type BoneData ¶
type BoneData struct {
// Name uniquely identifies the bone in the skeleton.
Name string
// Parent is the parent bone's Name, or empty for a root bone.
Parent string
// X and Y are the bone's bind-pose offset in its parent's space.
X, Y float32
// Rotation is the bone's bind-pose rotation in radians, clockwise on the screen.
Rotation float32
// ScaleX and ScaleY are the bone's bind-pose scales, 1 when omitted in the file.
ScaleX, ScaleY float32
// Length is an optional bone length for editors and debug overlays.
Length float32
}
BoneData describes one bone's bind pose relative to its parent.
type BoneTimeline ¶
type BoneTimeline struct {
Translate []Vec2Keyframe
Rotate []FloatKeyframe
Scale []Vec2Keyframe
}
BoneTimeline holds the optional transform tracks for one bone, applied relative to its bind pose: Translate and Rotate add; Scale multiplies.
type BoneTransform ¶
BoneTransform is a bone's position, rotation and scale in a drawing's coordinates.
type CurveType ¶
type CurveType uint8
CurveType selects how a keyframe interpolates to the next keyframe.
type FloatKeyframe ¶
FloatKeyframe is a scalar keyframe (rotation angle in radians or slot alpha).
type MeshAttachment ¶
type MeshAttachment struct {
Frame string
UVs []float32
Vertices []float32
Triangles []uint16
Weights [][]MeshWeight
}
MeshAttachment is a CPU-deformed weighted triangle mesh in attachment space.
func (MeshAttachment) Validate ¶
func (m MeshAttachment) Validate(bones map[string]bool) error
Validate reports an error unless the mesh has one UV per vertex, finite vertex and UV values, whole triangles indexing existing vertices, and for each vertex one to four finite, non-negative weights on bones in bones that sum to 1.
func (MeshAttachment) ValidateDeformOffsets ¶
func (m MeshAttachment) ValidateDeformOffsets(offsets []float32) error
ValidateDeformOffsets checks optional per-vertex offsets before deformation. Offsets must contain one x/y pair per vertex or be empty. A partial or oversized offset slice is rejected rather than silently producing a partial deformation.
type MeshWeight ¶
MeshWeight is how strongly one bone moves a mesh vertex.
type Skeleton ¶
type Skeleton struct {
// X and Y place the skeleton's root origin in the drawing.
X, Y float32
// Rotation turns the skeleton about its root origin, in radians, clockwise on the screen.
Rotation float32
// ScaleX and ScaleY scale the skeleton about its root origin; a negative value mirrors it.
ScaleX, ScaleY float32
// FlipX and FlipY mirror the skeleton across its root axes before Rotation.
FlipX, FlipY bool
// Alpha multiplies every slot's opacity, from 0 (draws nothing) to 1.
Alpha float32
// Tint multiplies every slot's sRGB and alpha channels before compositing, as sprite.Sprite.Tint does.
// The zero value and opaque white leave slots untinted; any other tint with alpha 0 draws nothing.
Tint core.Color
// Z is passed to each sprite drawn by Draw.
Z int
OnEvent func(animation, name string)
// contains filtered or unexported fields
}
Skeleton is a live instance of a SkeletonData rig: its root placement, active skin, per-slot attachment overrides, animation playback and computed bone transforms.
NewSkeleton returns a skeleton at full size and opacity in bind pose, with the "default" skin active when the rig defines one.
Example ¶
A Skeleton plays a rig's animations; WorldBone gives a bone's place after the bones above it have moved, here the hand after the arm is raised.
package main
import (
"fmt"
"time"
"github.com/nsgo-dev/game/pkg/skeletal"
)
// rig is a two-bone arm with a "raise" animation that lifts the upper arm over half a second.
const rig = `{
"version": 1,
"name": "arm",
"bones": [
{"name": "shoulder"},
{"name": "upper", "parent": "shoulder", "length": 10},
{"name": "hand", "parent": "upper", "x": 10, "length": 4}
],
"slots": [{"name": "upper", "bone": "upper"}],
"skins": {"default": {"upper": {"frame": "sleeve"}}},
"animations": {
"raise": {
"duration": 0.5,
"bones": {"upper": {"rotate": [{"time": 0, "angle": 0}, {"time": 0.5, "angle": -1.5707964}]}}
}
}
}`
func main() {
data, _ := skeletal.Load([]byte(rig))
s := skeletal.NewSkeleton(data, nil)
s.X, s.Y = 100, 100
s.UpdateWorldTransforms()
hand, _ := s.WorldBone("hand")
fmt.Printf("hand at (%.1f, %.1f)\n", hand.X, hand.Y)
if err := s.Play("raise", false); err != nil {
fmt.Println(err)
return
}
for range 40 {
s.Update(time.Second / 60)
}
s.UpdateWorldTransforms()
hand, _ = s.WorldBone("hand")
fmt.Printf("hand at (%.1f, %.1f), done %v\n", hand.X, hand.Y, s.Done())
}
Output: hand at (110.0, 100.0) hand at (100.0, 90.0), done true
func NewSkeleton ¶
func NewSkeleton(data *SkeletonData, atlas *sprite.Atlas) *Skeleton
NewSkeleton returns a skeleton for data drawing frames from atlas, at full scale and opacity in its bind pose. If data defines a "default" skin, it is active initially.
NewSkeleton panics when data does not compile, such as a hand-built SkeletonData with a duplicate bone name, an unknown parent or a cycle: an invalid rig would otherwise render every bone at the drawing's origin and report nothing.
func (*Skeleton) Animation ¶
Animation returns the name of the active (or incoming) animation, or empty when no animation is playing.
func (*Skeleton) ClearAttachment ¶
ClearAttachment removes any manual override set on slot by SetAttachment, returning it to the active animation or skin attachment.
func (*Skeleton) Crossfade ¶
Crossfade smoothly blends from the current pose into the named animation over duration, using shortest-angle rotation blending and linear translation, scale and alpha blending. If duration <= 0, Crossfade switches immediately like Play.
func (*Skeleton) Data ¶
func (s *Skeleton) Data() *SkeletonData
Data returns the immutable SkeletonData this skeleton was created from.
func (*Skeleton) Draw ¶
Draw updates world transforms and draws every visible slot into d in slot draw order through a reusable sprite.Batch.
func (*Skeleton) Play ¶
Play starts playing the named animation from time 0, cancelling any active crossfade, applies its initial pose and updates world transforms.
func (*Skeleton) ResetToBindPose ¶
func (s *Skeleton) ResetToBindPose()
ResetToBindPose restores every bone and slot to its bind pose, clears any active animation or crossfade, and updates world transforms.
func (*Skeleton) SetAttachment ¶
SetAttachment overrides the atlas frame drawn by slot. An empty frame hides the slot. Unknown slot names are ignored.
func (*Skeleton) SetSkin ¶
SetSkin switches the active skin to name. Slots missing from name fall back to the "default" skin. It returns an error if data does not define name.
func (*Skeleton) Update ¶
Update advances the active animation (and any ongoing crossfade) by dt and updates every bone's world transform. Call it from a game.Loop's fixed-step Update callback for deterministic playback.
func (*Skeleton) UpdateWorldTransforms ¶
func (s *Skeleton) UpdateWorldTransforms()
UpdateWorldTransforms computes every bone's world transform down the parent-child tree from the skeleton's root transform and current local pose.
type SkeletonData ¶
type SkeletonData struct {
// Version is the schema version of the rig, FormatVersion.
Version int
// Name is the rig's name, if the file gave one.
Name string
// Bones are the rig's bones in bind pose.
Bones []BoneData
// Slots are the rig's slots in draw order, back to front.
Slots []SlotData
// Skins maps each skin's name to the attachments it places on slots.
Skins map[string]Skin
// Animations maps each animation's name to its timelines.
Animations map[string]*Animation
// contains filtered or unexported fields
}
SkeletonData is the immutable description of a 2D skeletal rig: its bones, draw-ordered slots, skins and animations. Share one SkeletonData across as many Skeleton instances as need it.
func Load ¶
func Load(data []byte) (*SkeletonData, error)
Load parses and validates a version-1 skeletal rig from YAML (.skel.yaml).
It rejects empty input, unknown fields, duplicate keys, trailing YAML documents, unknown schema versions, non-finite numbers, duplicate bone or slot names, missing parents, cycles in the bone hierarchy, slots or skins referencing missing bones or slots, and animations with unknown targets, unsorted or out-of-range keyframes, or invalid curves. A version-1 rig written as JSON loads too when the JSON is also valid YAML: keys spelled exactly as the schema spells them (matching is case-sensitive) and no `\/` escape, which YAML does not have.
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 ¶
Load reads and validates a rig, refusing unknown versions, cycles and references to missing bones.
package main
import (
"fmt"
"github.com/nsgo-dev/game/pkg/skeletal"
)
// rig is a two-bone arm with a "raise" animation that lifts the upper arm over half a second.
const rig = `{
"version": 1,
"name": "arm",
"bones": [
{"name": "shoulder"},
{"name": "upper", "parent": "shoulder", "length": 10},
{"name": "hand", "parent": "upper", "x": 10, "length": 4}
],
"slots": [{"name": "upper", "bone": "upper"}],
"skins": {"default": {"upper": {"frame": "sleeve"}}},
"animations": {
"raise": {
"duration": 0.5,
"bones": {"upper": {"rotate": [{"time": 0, "angle": 0}, {"time": 0.5, "angle": -1.5707964}]}}
}
}
}`
func main() {
data, err := skeletal.Load([]byte(rig))
if err != nil {
fmt.Println(err)
return
}
fmt.Println(data.Name, len(data.Bones), len(data.Animations))
_, err = skeletal.Load([]byte(`{"version": 2, "name": "x"}`))
fmt.Println(err != nil)
}
Output: arm 3 1 true
func (*SkeletonData) Compile ¶
func (sd *SkeletonData) Compile() error
Compile validates cross-references in a hand-built SkeletonData and builds the dense lookup indices and topological bone evaluation order its runtime needs. Data loaded from a document is compiled already, and calling Compile again is harmless.
type SlotData ¶
type SlotData struct {
// Name uniquely identifies the slot in the skeleton.
Name string
// Bone is the name of the bone whose transform the slot follows.
Bone string
// Attachment is an optional default atlas frame name when no skin supplies one.
Attachment string
// Alpha is the slot's bind-pose opacity in [0, 1], 1 when omitted in the file.
Alpha float32
}
SlotData describes one draw slot attached to a bone.
type SlotTimeline ¶
type SlotTimeline struct {
Attachment []AttachmentKeyframe
Alpha []FloatKeyframe
}
SlotTimeline holds the optional attachment and opacity tracks for one slot.