Animation Controller
Automatic switching between skeletal animations, driven by input or by your own state variables.
Component: TGorillaAnimationController
Unit: Gorilla.Animation.Controller
Table of Contents
- Introduction
- Architecture
- Getting Started
- Transitions
- Layers
- Dispatching Input
- One-Shot Animations
- Complete Example: Hit Reactions
- Complete Example: Idle / Run
- Saving and Loading
- Design-Time Transition Editor
- Troubleshooting
- Best Practices
- See Also
Introduction
A character usually consists of one mesh and many animation clips - idle, run,
jump, hit, die. Playing them by hand means calling PlayAnimation() from every
place that can change the character state, and keeping track of which clip is allowed
to follow which.
TGorillaAnimationController replaces that with a small state machine: you declare
transitions ("from clip A to clip B, when X happens"), and afterwards you only
dispatch what happened. The controller decides whether a transition matches the
currently playing clip and performs the switch.
Key features:
- Declarative transitions -
A -> B when <condition>instead of scattered playback calls - Two trigger sources - character controller hotkeys plus movement states, or your own named variables
- Layers - group transitions so complex characters stay readable
- Switch modes - switch immediately or wait until the running clip has finished
- One-shot clips - non-looping animations automatically re-evaluate the transitions when they end
- Persistence - the complete setup serializes to and from JSON
- Design-time editor - a flow-chart editor for transitions inside the IDE
- Automatic integration -
TGorillaPhysicsCharacterControllerfeeds its state in for you
Architecture
TGorillaAnimationController (Model, DefaultAnimation)
└─ Layers : TGorillaAnimationTransitionLayerCollection
└─ TGorillaAnimationTransitionLayer ("Layer0", "Layer1", ...)
└─ Transitions : TGorillaAnimationTransitionCollection
└─ TGorillaAnimationTransition (AnimationFrom -> AnimationTo)
The controller does not own the animations. It works on the TGorillaAnimationManager
of the linked TGorillaModel, and switching means setting
Model.AnimationManager.Current and starting that animation.
A dispatch always runs through every layer, and every layer evaluates against the animation that is current at that moment.
Getting Started
Design-Time Setup
- Drop a
TGorillaModelonto your viewport and load a character into it - Drop a
TGorillaAnimationControlleronto the form - Set its
Modelproperty to the model component - Set
DefaultAnimationto the ID of the clip that should play initially - Open the transition editor from the component's context menu (Transition Editor)
Runtime Setup
uses
Gorilla.Animation, Gorilla.Animation.Controller;
const
CHARACTER_MODEL = 'c.dae';
CHARACTER_IDLE = 'c-idle.dae';
CHARACTER_RUN = 'c-run.dae';
procedure TForm1.SetupCharacter();
var
LPckg : TGorillaAssetsPackage;
LPath : String;
LAnim : TGorillaAnimation;
LLay : TGorillaAnimationTransitionLayer;
begin
LPckg := GorillaAssetsManager1.AddEmptyPackage('Cache');
LPath := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0)))
+ IncludeTrailingPathDelimiter('assets');
// 1) load the model and the additional animation clips
GorillaModel1.LoadFromFile(LPckg, LPath + CHARACTER_MODEL, []);
LAnim := GorillaModel1.AddAnimationFromFile(LPath + CHARACTER_IDLE, []);
GorillaModel1.AddAnimationFromFile(LPath + CHARACTER_RUN, []);
LAnim.Start();
// 2) link the model, then set the default animation
GorillaAnimationController1.Model := GorillaModel1;
GorillaAnimationController1.DefaultAnimation := CHARACTER_IDLE;
// 3) create a layer and declare the transitions
LLay := GorillaAnimationController1.AddLayer('Layer0');
LLay.AddTransition('idle > run', CHARACTER_IDLE, CHARACTER_RUN, true,
TGorillaCharacterControllerHotKey.KeyboardMoveForward,
[TGorillaCharacterControllerState.fpMoving],
TGorillaAnimationTransitionMode.tmImmediatly);
end;
Order matters: assign
ModelbeforeDefaultAnimation. SettingDefaultAnimationresolves the clip through the model's animation manager, makes it the current animation and starts it right away. Without a model the assignment is remembered as a string but nothing is started.
Animation IDs
Transitions reference animations by ID, not by object. The ID is the one the
animation manager registered the clip under - for clips added with
AddAnimationFromFile() that is the file name, e.g. c-idle.dae. Declaring the IDs
as constants keeps the transition table readable:
const
MODEL_ANIM_IDLE = 'c-idle.dae';
MODEL_ANIM_HIT1 = 'c-hit1.dae';
References are resolved lazily against Model.AnimationManager. A transition that
names a clip which is not loaded yet stays unresolved and simply never triggers, so
load all clips before (or at least right after) declaring the transitions.
Transitions
A TGorillaAnimationTransition answers three questions:
| Question | Properties |
|---|---|
| From where to where? | AnimationFrom, AnimationTo |
| When? | DetectionKind plus HotKey / States or Variable / Value |
| How? | Mode, Loop |
Detection Kinds
TGorillaAnimationTransitionDetectionKind selects what a transition listens to:
| Value | Triggered by | Evaluated properties |
|---|---|---|
tkHotKeyAndStates |
A character controller hotkey plus the active character states | HotKey, States |
tkCustom |
A named variable and its value | Variable, Value |
You do not normally set DetectionKind yourself - the AddTransition() overload you
choose sets it for you.
State matching is a subset test. The transition fires when all states listed in
States are contained in the dispatched state set; the dispatched set may contain
more. States := [] therefore matches any state, and the hotkey alone decides.
Values are compared as strings. Value stores TValue.ToString(), so the integer
1 and the string '1' are the same condition.
Transition Modes
TGorillaAnimationTransitionMode defines how the switch happens:
| Mode | Behaviour |
|---|---|
tmImmediatly |
The destination clip becomes current and starts right away, cutting the running clip |
tmSequentially |
The running clip is set to non-looping and plays to its end; the destination clip starts afterwards |
tmBlend |
Reserved for cross-fading. Not implemented yet - currently behaves like tmSequentially |
OffsetAnimationFrom, OffsetAnimationTo and Duration describe the blend window for
tmBlend. They are stored and serialized, but have no effect until blending is
implemented.
The engine does have a crossfade, but it lives on
TGorillaAnimationManagerand is triggered byPlayAnimation(). The controller switches by assigningAnimationManager.Current, which bypasses it. See Animation Playback Control for the blend settings and for a pattern that combines the controller's transition table with crossfading.
Use
tmImmediatlyfor responsive movement (idle and run must react on the same frame) andtmSequentiallywhen a clip must not be interrupted, e.g. a reload or an attack wind-up.
Loop
Loop applies to the destination clip:
Loop = true- the destination clip repeats until another transition switches awayLoop = false- the destination clip plays once; when it ends the controller re-evaluates the transitions (see One-Shot Animations)
Adding Transitions
Both TGorillaAnimationController and TGorillaAnimationTransitionLayer offer
AddTransition(). The controller variant takes the layer name as first argument and
requires the layer to exist already.
// hotkey + states variant
LLay.AddTransition('idle > run', IDLE, RUN, true,
TGorillaCharacterControllerHotKey.KeyboardMoveForward,
[TGorillaCharacterControllerState.fpMoving],
TGorillaAnimationTransitionMode.tmImmediatly);
// custom variable variant
LLay.AddTransition('idle > hit1', IDLE, HIT1, false,
'anim', 1,
TGorillaAnimationTransitionMode.tmImmediatly);
Transitions can be looked up and removed again:
LTr := GorillaAnimationController1.FindTransition('Layer0', 'idle > run');
LTr := GorillaAnimationController1.FindTransition('Layer0', IDLE, RUN);
GorillaAnimationController1.DeleteTransition('Layer0', 'idle > run');
GorillaAnimationController1.DeleteTransition('Layer0', IDLE, RUN);
Layers
A model with a dozen clips produces dozens of transitions. Layers group them so each group stays readable - for example one layer for "starting to move", one for "coming back to rest", one for combat.
LLay := GorillaAnimationController1.AddLayer('Movement');
// ...
if GorillaAnimationController1.LayerExists('Movement') then
GorillaAnimationController1.RemoveLayer('Movement');
AddLayer() returns the existing layer if the name is already in use, so calling it
twice never produces duplicates.
How layers interact: a dispatch is forwarded to every layer in collection order. Each layer looks at the current animation and may switch it - which means a later layer already sees the result of an earlier one. Within a single layer the first matching transition wins and evaluation stops.
Design your layers so that only one of them can match a given situation. In the
physics demo this is done by making the leave transitions depend on
UnknownHotKey + fpIdle, which cannot be true while a movement hotkey is dispatched.
Dispatching Input
Nothing happens until you dispatch. All four overloads exist on the controller, on a single layer, and on the layer collection:
procedure DispatchInput(ADispatcher : TGorillaAnimationDispatcher); overload;
procedure DispatchInput(AHotKey : TGorillaCharacterControllerHotKey;
AStates : TGorillaCharacterControllerStates); overload;
procedure DispatchInput(AVariable : String; AValue : String); overload;
procedure DispatchInput(AVariable : String; AValue : TValue); overload;
The last dispatch is remembered in the controller's DispatchState property and is
replayed automatically when a one-shot clip ends.
Custom Variables
Use this when the trigger is game logic rather than input - a hit, a spell, a phase change:
procedure TForm2.Button2Click(Sender: TObject);
begin
GorillaAnimationController1.DispatchInput('anim', 1);
end;
Any TValue-compatible value works; it is compared by its string representation.
HotKeys and States
Use this when animation should follow character movement:
GorillaAnimationController1.DispatchInput(
TGorillaCharacterControllerHotKey.KeyboardMoveForward,
[TGorillaCharacterControllerState.fpMoving]);
TGorillaCharacterControllerHotKey and TGorillaCharacterControllerState are declared
in Gorilla.Controller.Input.Types and are the same values a first- or third-person
controller reports.
Automatic Dispatch by Character Controllers
TGorillaPhysicsCharacterController dispatches for you. Link both components and the
character's movement drives the animations without a single line of playback code:
GorillaPhysicsCharacterController1.Model := GorillaModel1;
GorillaPhysicsCharacterController1.Controller := GorillaThirdPersonController1;
GorillaPhysicsCharacterController1.AnimationController := GorillaAnimationController1;
Every character state change is forwarded as
AnimationController.DispatchInput(AHotKey, AStates). Both Model and
AnimationController must be assigned, otherwise the dispatch is skipped.
One-Shot Animations
A transition with Loop = false and Mode = tmImmediatly starts the destination clip
once. When it finishes, the controller sets that clip back to looping and re-runs the
last dispatch against the transitions. This is how a character returns from a one-shot
clip: you declare the way back with the same condition.
// out: idle -> hit1, plays once
FLayer1.AddTransition('idle > hit1', IDLE, HIT1, false,
'anim', 1, TGorillaAnimationTransitionMode.tmImmediatly);
// back: when hit1 has finished, the same dispatch ('anim' = 1) is replayed,
// now with hit1 as current animation - so this one matches and loops idle
FLayer1.AddTransition('hit1 > idle', HIT1, IDLE, true,
'anim', 1, TGorillaAnimationTransitionMode.tmImmediatly);
Without the second transition the character would stay in its final hit pose.
In tmSequentially mode the mechanism is different: the running clip is set to
non-looping and the destination starts when it ends, so no replay is needed.
Complete Example: Hit Reactions
From the AnimationController demo: one rest-pose model plus three clips, switched by a custom variable from two buttons.
const
MODEL_ANIM_NONE = 'c.dae';
MODEL_ANIM_IDLE = 'c-idle.dae';
MODEL_ANIM_HIT1 = 'c-hit1.dae';
MODEL_ANIM_HIT2 = 'c-hit2.dae';
procedure TForm2.FormCreate(Sender: TObject);
var
LPath : String;
LPckg : TGorillaAssetsPackage;
LOpts : TGorillaLoadOptions;
begin
LPath := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0)))
+ IncludeTrailingPathDelimiter('assets');
LPckg := GorillaAssetsManager1.AddEmptyPackage('TempPackage');
LOpts := TGorillaLoadOptions.Create(LPath + MODEL_ANIM_NONE, LPckg);
GorillaModel1.LoadFromFile(LOpts);
GorillaModel1.AddAnimationFromFile(LPath + MODEL_ANIM_IDLE);
GorillaModel1.AddAnimationFromFile(LPath + MODEL_ANIM_HIT1);
GorillaModel1.AddAnimationFromFile(LPath + MODEL_ANIM_HIT2);
AddCustomTransitions();
end;
procedure TForm2.AddCustomTransitions();
begin
GorillaAnimationController1.DefaultAnimation := MODEL_ANIM_IDLE;
FLayer1 := GorillaAnimationController1.AddLayer('Layer1');
// hit 1: play once, then return to looping idle
FLayer1.AddTransition('idle > hit1', MODEL_ANIM_IDLE, MODEL_ANIM_HIT1, false,
'anim', 1, TGorillaAnimationTransitionMode.tmImmediatly);
FLayer1.AddTransition('hit1 > idle', MODEL_ANIM_HIT1, MODEL_ANIM_IDLE, true,
'anim', 1, TGorillaAnimationTransitionMode.tmImmediatly);
// hit 2: same pattern
FLayer1.AddTransition('idle > hit2', MODEL_ANIM_IDLE, MODEL_ANIM_HIT2, false,
'anim', 2, TGorillaAnimationTransitionMode.tmImmediatly);
FLayer1.AddTransition('hit2 > idle', MODEL_ANIM_HIT2, MODEL_ANIM_IDLE, true,
'anim', 2, TGorillaAnimationTransitionMode.tmImmediatly);
// allow interrupting one hit with the other
FLayer1.AddTransition('hit2 > hit1', MODEL_ANIM_HIT2, MODEL_ANIM_HIT1, false,
'anim', 1, TGorillaAnimationTransitionMode.tmImmediatly);
FLayer1.AddTransition('hit1 > hit2', MODEL_ANIM_HIT1, MODEL_ANIM_HIT2, false,
'anim', 2, TGorillaAnimationTransitionMode.tmImmediatly);
end;
procedure TForm2.Button2Click(Sender: TObject);
begin
GorillaAnimationController1.DispatchInput('anim', 1);
end;
procedure TForm2.Button3Click(Sender: TObject);
begin
GorillaAnimationController1.DispatchInput('anim', 2);
end;
Note the pairs: every out transition (Loop = false) has a matching back
transition using the same variable value, because the value is replayed when the
one-shot clip ends.
The demo links GorillaAnimationController1.Model to GorillaModel1 at design time,
which is why the code never assigns Model itself.
See demos/AnimationController.
Complete Example: Idle / Run
From the PhysicsCharacterControllerDemo: no manual dispatch at all - the physics character controller feeds the animation controller, and two layers split "start moving" from "stop moving".
const
CHARACTER_MODEL = 'c.dae';
CHARACTER_IDLE = 'c-idle.dae';
CHARACTER_RUN = 'c-run.dae';
procedure TForm1.DoCreateCharacter();
var
LPath : String;
LAnim : TGorillaAnimation;
LLay : TGorillaAnimationTransitionLayer;
begin
FPackage := GorillaAssetsManager1.AddEmptyPackage('Cache');
LPath := GetAssetsPath();
GorillaModel1.LoadFromFile(FPackage, LPath + CHARACTER_MODEL, []);
LAnim := GorillaModel1.AddAnimationFromFile(LPath + CHARACTER_IDLE, []);
GorillaModel1.AddAnimationFromFile(LPath + CHARACTER_RUN, []);
LAnim.Start();
GorillaAnimationController1.DefaultAnimation := CHARACTER_IDLE;
// layer 0: any movement key while moving -> run
LLay := GorillaAnimationController1.AddLayer('Layer0');
LLay.AddTransition('idle > run-forward', CHARACTER_IDLE, CHARACTER_RUN, true,
TGorillaCharacterControllerHotKey.KeyboardMoveForward,
[TGorillaCharacterControllerState.fpMoving],
TGorillaAnimationTransitionMode.tmImmediatly);
LLay.AddTransition('idle > run-backward', CHARACTER_IDLE, CHARACTER_RUN, true,
TGorillaCharacterControllerHotKey.KeyboardMoveBackward,
[TGorillaCharacterControllerState.fpMoving],
TGorillaAnimationTransitionMode.tmImmediatly);
LLay.AddTransition('idle > run-left', CHARACTER_IDLE, CHARACTER_RUN, true,
TGorillaCharacterControllerHotKey.KeyboardMoveLeft,
[TGorillaCharacterControllerState.fpMoving],
TGorillaAnimationTransitionMode.tmImmediatly);
LLay.AddTransition('idle > run-right', CHARACTER_IDLE, CHARACTER_RUN, true,
TGorillaCharacterControllerHotKey.KeyboardMoveRight,
[TGorillaCharacterControllerState.fpMoving],
TGorillaAnimationTransitionMode.tmImmediatly);
// layer 1: no key, character idle -> back to idle clip
LLay := GorillaAnimationController1.AddLayer('Layer1');
LLay.AddTransition('run > idle', CHARACTER_RUN, CHARACTER_IDLE, true,
TGorillaCharacterControllerHotKey.UnknownHotKey,
[TGorillaCharacterControllerState.fpIdle],
TGorillaAnimationTransitionMode.tmImmediatly);
end;
The Layer0 transitions cannot fire while the character is idle (no movement hotkey is
dispatched), and the Layer1 transition cannot fire while a movement hotkey is
dispatched - the two layers are mutually exclusive by construction.
The demo declares the Layer1 transition once per movement direction. That is optional:
all four use the identical condition (UnknownHotKey + fpIdle), so a single
transition is enough. As in the other demo, Model and the link from
GorillaPhysicsCharacterController1.AnimationController are set at design time.
See demos/PhysicsCharacterControllerDemo.
Saving and Loading
The whole setup - linked model, default animation, layers and transitions - serializes to JSON:
GorillaAnimationController1.SaveToFile('character.animctrl');
// ...
GorillaAnimationController1.LoadFromFile('character.animctrl', FPackage);
Stream variants (SaveToStream / LoadFromStream) and the raw JSON level
(ToJSON / FromJSON) are available as well.
On loading, the controller tries to reconnect the model in this order:
- a component with the stored model ID, searched in the owner and its children
- an existing
TGorillaModelwhoseSourceequals the stored file name - otherwise the model is loaded from the stored file name into a standalone model owned by the controller, and all listed animation files are loaded next to it
If the model cannot be restored, or an animation file listed in the JSON is missing, an
exception is raised. Pass a TGorillaAssetsPackage to LoadFromFile / LoadFromStream
so auto-loaded models and textures end up in the package you expect.
Design-Time Transition Editor
With the design package installed, the controller's context menu offers Transition
Editor: a flow-chart view of the layers, the animations they reference and the
transitions between them. The node positions are stored per layer (UIPosition) and
serialized with the rest of the setup, so a hand-arranged graph survives save and load.
Troubleshooting
Nothing switches at all.
Check in this order: is Model assigned, is DefaultAnimation a valid ID and did it
actually start, are the transition IDs spelled exactly like the registered animation
IDs, and are you dispatching?
A transition only works the first time. A non-looping destination clip needs a way back. Add the reverse transition, see One-Shot Animations.
Transitions added later do not trigger. For hotkey detection, the collection builds an internal lookup map on first use. After adding or changing transitions at runtime, rebuild it:
LLay.Transitions.UpdateHashMap();
FindTransition(<name>) returns nil although the transition exists.
The by-name lookup searches that same map. Call UpdateHashMap() first, or look the
transition up by animation pair with FindTransition(AFrom, ATo), which always scans
the collection.
The wrong transition fires.
Transitions from the same animation with the same hotkey share one lookup bucket and are
tested in collection order - the first one whose states are a subset of the dispatched
states wins. Declare the more specific transition (larger States set) before the
general one.
Enabled = False and it still switches.
The inherited Enabled property does not gate transitions - dispatching works
regardless. Stop feeding dispatches (or clear the layers) if you want to freeze the
state machine.
Two layers fight over the same clip. Remember that layers run in order and each sees the result of the previous one. Make the conditions mutually exclusive.
Best Practices
1. Declare Animation IDs as Constants
They are used in the transitions, in DefaultAnimation and in the JSON. A typo in a
string fails silently.
2. Link the Model First
Model then DefaultAnimation then layers and transitions. Every step after the first
resolves references through the model's animation manager.
3. One Layer per Concern
Movement, combat, emotes. Keep each layer small enough to read at a glance and make the conditions of different layers mutually exclusive.
4. Pair Every One-Shot Clip
Loop = false always needs a matching transition back, triggered by the same condition.
5. Prefer tmImmediatly for Movement
Movement has to react on the same frame. Reserve tmSequentially for clips that must
play out completely.
6. Treat tmBlend as tmSequentially
Cross-fading is not implemented yet. Do not rely on OffsetAnimationFrom,
OffsetAnimationTo or Duration having a visible effect.
7. Let the Character Controller Dispatch
For player characters, link TGorillaPhysicsCharacterController.AnimationController
instead of dispatching hotkeys by hand.
8. Keep Conditions Cheap and Coarse
A dispatch walks all layers. Use a few well-chosen variables rather than one variable per animation.
See Also
- Gorilla.Animation.Controller Unit - Full API documentation
- Animation Playback Control - Speed, seeking to a position, crossfading, morphing
- Gorilla.Animation Unit - The underlying animation system
- Input Polling System - HotKeys, sequences and devices
- Camera & Character Controllers - First- and third-person controllers
- Physics - Physics character controller
- Models - Loading models and additional animation clips