Animation

Gorilla3D provides a comprehensive animation system for bringing 3D scenes to life. The framework supports multiple animation types including skeletal/joint animation, vertex (mesh) animation, and property-based keyframe animation for transforming objects over time.

Animation Architecture

Key Components

TGorillaAnimationManager (Component)
└─ TGorillaAnimation Collection
   └─ TSkeletonKeyAnimation (Container)
      └─ TPropertyKeyAnimation instances
         ├─ TPoint3DKeyAnimation
         ├─ TVector3DKeyAnimation
         ├─ TQuaternion3DKeyAnimation
         ├─ TTransformationKeyAnimation
         └─ TCoordinateKeyAnimation

Animation Types

Gorilla3D supports several animation types:

Type Description Use Case
TPoint3DKeyAnimation Animates TPoint3D properties Position, rotation, scale transforms
TVector3DKeyAnimation Animates TVector3D properties Directional transforms
TQuaternion3DKeyAnimation Animates quaternion rotations Smooth rotations without gimbal lock
TTransformationKeyAnimation Animates full TMatrix3D transforms Skeletal/joint animation
TCoordinateKeyAnimation Animates vertex positions Mesh morphing, vertex animation
TSkeletonKeyAnimation Container for synchronized animations Character animation, complex rigs

Animation Manager

The TGorillaAnimationManager is the central component for managing all animations associated with a 3D model or character.

Basic Setup

A TGorillaAnimationManager instance will automatically be created, loading model data into a TGorillaModel component. The model component will take care of registering animations and setting up all necessary animations. Basically a TGorillaAnimationManager manages multiple TGorillaAnimation objects, which then hold multiple animation types.

Runtime

In special cases it might be needed to instanciate a TGorillaAnimationManager object manually. In order to do that, follow this workflow.

var
  Manager: TGorillaAnimationManager;
  Animation: TGorillaAnimation;
begin
  // the owner must be the mesh/model the animations belong to -
  // the constructor casts it to TGorillaMesh and assigns it to Manager.Mesh
  Manager := TGorillaAnimationManager.Create(GorillaModel1);

  // Load animation from definition
  Animation := TGorillaAnimation.CreateEx(Manager);
  Animation.LoadFromAnimationDef(AnimationDef);
  Manager.AddAnimation('Walk', Animation);
end;

The manager owns its animations - removing them from Animations or calling Clear() frees them.

Listing Animations

Animations is a hashmap, so enumerating it directly yields an arbitrary order that can change whenever an animation is added. For anything shown to a user, ask the manager for a sorted list instead:

var
  LName: String;
  LAnim: TGorillaAnimation;
begin
  // ids only - e.g. to fill a combo box
  ComboBox1.Clear();
  for LName in GorillaModel1.AnimationManager.GetAnimationNames() do
    ComboBox1.Items.Add(LName);

  // or the instances themselves, in the same order
  for LAnim in GorillaModel1.AnimationManager.GetSortedAnimations() do
    Memo1.Lines.Add(Format('%s: %.2f s', [LAnim.Id, LAnim.Skeleton.Duration]));
end;

Both return a snapshot as a dynamic array - nothing to free. The instances in GetSortedAnimations() still belong to the manager.

The order is natural: digit runs are compared by their numeric value, text case-insensitively. Walk2 comes before Walk10, idle and Idle sort together, and the result is deterministic on every platform.

Registered:   Walk10, idle, Walk2, Run, Attack01
Sorted:       Attack01, idle, Run, Walk2, Walk10

Playing Animations

By Name

// Play a specific animation
Manager.PlayAnimation('Walk');

// Check current animation
if Manager.CurrentAnimationName = 'Run' then
  ShowMessage('Character is running');

By Instance

var
  WalkAnim: TGorillaAnimation;
begin
  WalkAnim := Manager.GetAnimation('Walk');
  if Assigned(WalkAnim) then
    Manager.PlayAnimation(WalkAnim);
end;

PlayAnimation is the switching path that crossfades from the current pose into the new clip (see Crossfading). Calling Start() on an animation or assigning Manager.Current switches hard. If the id is not found, PlayAnimation returns nil and the current clip keeps playing.

The id of an animation loaded from a file is the file name, f.e. archer-idle.dae. Use TGorillaAnimation.Id (or Manager.GetAnimationNames()) to list animations, not Name: Name is the component name, which can not contain dots or dashes (archer_idle_dae). GetAnimation and PlayAnimation accept the component name as fallback anyway.

// fill a combobox with all animations, naturally sorted
for var LAnim : TGorillaAnimation in Manager.GetSortedAnimations() do
  ComboBox1.Items.Add(LAnim.Id);

// ... and play the selected one
Manager.PlayAnimation(ComboBox1.Items[ComboBox1.ItemIndex]);

Sequential Playback

The navigation routines walk the animations in the natural order of GetAnimationNames() - not in the order they were added and not in hashmap order:

// registered ids: 'Walk10', 'Idle', 'Walk2'
Manager.PlayAnimation('Idle');

Manager.PlayNextAnimation();      // Walk2
Manager.PlayNextAnimation();      // Walk10
Manager.PlayNextAnimation();      // Idle   - wraps around to the first

Manager.PlayPreviousAnimation();  // Walk10 - wraps around to the last
Method Result
GetFirstAnimation() / GetLastAnimation() First / last animation in natural id order, nil if empty
PlayNextAnimation() Next animation, wraps to the first; starts the first one if none is current
PlayPreviousAnimation() Previous animation, wraps to the last; starts the last one if none is current

Both play methods go through PlayAnimation and therefore crossfade as well.

In earlier builds these routines followed the internal hash order, which was unpredictable. If you relied on "first added = first played", name your clips so that their natural order is the intended one (e.g. 01-Idle, 02-Walk, 10-Jump).

Animation Control

// Get current animation
var CurrentAnim := Manager.Current;

if Assigned(CurrentAnim) then
begin
  // Start animation
  CurrentAnim.Start();

  // Stop animation (FMX jumps to the final frame first)
  CurrentAnim.Stop();

  // Stop and keep the currently visible pose
  CurrentAnim.StopAtCurrent();

  // Reset to first frame
  CurrentAnim.Reset();

  // Scale the interpolator durations - NOTE: a duration factor,
  // 2.0 = twice as long = half speed, and cumulative
  CurrentAnim.SetSpeed(0.5);

  // Check animation state
  if CurrentAnim.IsRunning then
    ShowMessage('Animation playing');

  if CurrentAnim.IsPaused then
    ShowMessage('Animation paused');
end;

Pausing

{$IF CompilerVersion >= 37.0}
  // Delphi 13+: the render clock occupies the FMX Pause flag
  CurrentAnim.Skeleton.Paused := True;
{$ELSE}
  CurrentAnim.Skeleton.Pause := True;
{$ENDIF}

IsPaused reads the right flag on every Delphi version. See Animation Playback Control for an absolute playback rate, seeking and crossfade settings.

Property Key Animations

Property key animations allow you to animate specific properties of 3D objects using keyframes.

TPoint3DKeyAnimation

Animates TPoint3D properties like Position, Scale, or Rotation.

Basic Example

var
  Anim: TPoint3DKeyAnimation;
  Key0, Key1, Key2: TPoint3DKey;
begin
  Anim := TPoint3DKeyAnimation.Create(Self);
  Anim.PropertyName := 'Position.Point';
  Anim.Duration := 2.0;
  Anim.Loop := True;

  // Add element to animate
  Anim.AddElement(Cube1, True);

  // Define keyframes
  Key0 := TPoint3DKey(Anim.Keys.Add);
  Key0.Time := 0.0;
  Key0.Value[Cube1] := Point3D(0, 0, 0);

  Key1 := TPoint3DKey(Anim.Keys.Add);
  Key1.Time := 0.5;
  Key1.Value[Cube1] := Point3D(0, 5, 0);

  Key2 := TPoint3DKey(Anim.Keys.Add);
  Key2.Time := 1.0;
  Key2.Value[Cube1] := Point3D(0, 0, 0);

  Anim.Start();
end;

Animating Multiple Objects

// Single animation controlling multiple objects
Anim.AddElement(Cube1, True);
Anim.AddElement(Cube2, True);
Anim.AddElement(Sphere1, True);

// Set different values per object in each key
Key0 := TPoint3DKey(Anim.Keys.Add);
Key0.Time := 0.0;
Key0.Value[Cube1] := Point3D(0, 0, 0);
Key0.Value[Cube2] := Point3D(5, 0, 0);
Key0.Value[Sphere1] := Point3D(-5, 0, 0);

Animation Properties

// Interpolation type
Anim.Interpolation := TInterpolationType.Linear;
// Options: Linear, Quadratic, Cubic, Quartic, Quintic,
//          Sinusoidal, Exponential, Circular, Elastic, Back, Bounce

// Animation type (easing)
Anim.AnimationType := TAnimationType.InOut;
// Options: In, Out, InOut

// Looping and reversing
Anim.Loop := True;          // Repeat animation
Anim.AutoReverse := True;   // Reverse playback at end
Anim.Inverse := False;      // Start from end to beginning

// Timing
Anim.Delay := 0.5;          // Delay before starting (seconds)
Anim.Duration := 2.0;       // Total animation duration

TVector3DKeyAnimation

Animates TVector3D properties. Usage is identical to TPoint3DKeyAnimation:

var
  Anim: TVector3DKeyAnimation;
  Key: TVector3DKey;
begin
  Anim := TVector3DKeyAnimation.Create(Self);
  Anim.PropertyName := 'Scale';
  Anim.Duration := 1.0;

  Key := TVector3DKey(Anim.Keys.Add);
  Key.Time := 0.0;
  Key.Value[Cube1] := Vector3D(1, 1, 1);

  Key := TVector3DKey(Anim.Keys.Add);
  Key.Time := 1.0;
  Key.Value[Cube1] := Vector3D(2, 2, 2);

  Anim.Start();
end;

TQuaternion3DKeyAnimation

Animates rotations using quaternions for smooth interpolation without gimbal lock:

var
  Anim: TQuaternion3DKeyAnimation;
  Key: TQuaternion3DKey;
  Quat: TQuaternion3D;
begin
  Anim := TQuaternion3DKeyAnimation.Create(Self);
  Anim.PropertyName := 'RotationAngle';
  Anim.Duration := 3.0;
  Anim.Loop := True;

  // Create quaternions from Euler angles
  Quat := TQuaternion3D.Create(Vector3D(0, 0, 0));
  Key := TQuaternion3DKey(Anim.Keys.Add);
  Key.Time := 0.0;
  Key.Value[Cube1] := Quat;

  Quat := TQuaternion3D.Create(Vector3D(0, 180, 0));
  Key := TQuaternion3DKey(Anim.Keys.Add);
  Key.Time := 1.0;
  Key.Value[Cube1] := Quat;

  Anim.Start();
end;

TTransformationKeyAnimation

Animates full transformation matrices, primarily used for skeletal animation:

var
  Anim: TTransformationKeyAnimation;
  Key: TTransformationKey;
  Matrix: TMatrix3D;
begin
  Anim := TTransformationKeyAnimation.Create(Self);
  Anim.PropertyName := 'LocalMatrix';
  Anim.AddElement(Joint1, True);

  Key := TTransformationKey(Anim.Keys.Add);
  Key.Time := 0.0;
  Matrix := TMatrix3D.CreateTranslation(Point3D(0, 0, 0));
  Key.Value[Joint1] := Matrix;

  Key := TTransformationKey(Anim.Keys.Add);
  Key.Time := 1.0;
  Matrix := TMatrix3D.CreateTranslation(Point3D(0, 5, 0)) *
            TMatrix3D.CreateRotationY(DegToRad(45));
  Key.Value[Joint1] := Matrix;

  Anim.Start();
end;

Skeletal Animation

Skeletal (or armature) animation uses bones/joints to deform a mesh. This is the standard approach for character animation.

TSkeletonKeyAnimation

TSkeletonKeyAnimation is a container that synchronizes multiple TPropertyKeyAnimation instances:

var
  SkeletonAnim: TSkeletonKeyAnimation;
  Joint1Anim, Joint2Anim: TTransformationKeyAnimation;
begin
  SkeletonAnim := TSkeletonKeyAnimation.Create(Self);
  SkeletonAnim.Duration := 2.0;
  SkeletonAnim.Loop := True;
  SkeletonAnim.AutoRepaint := True;  // Auto-update viewport

  // Create joint animations
  Joint1Anim := TTransformationKeyAnimation.Create(Self);
  Joint1Anim.PropertyName := 'LocalMatrix';
  Joint1Anim.AddElement(ArmJoint, True);
  // ... add keys for Joint1Anim

  Joint2Anim := TTransformationKeyAnimation.Create(Self);
  Joint2Anim.PropertyName := 'LocalMatrix';
  Joint2Anim.AddElement(LegJoint, True);
  // ... add keys for Joint2Anim

  // Add to skeleton container
  SkeletonAnim.AddInterpolator(Joint1Anim);
  SkeletonAnim.AddInterpolator(Joint2Anim);

  // Start synchronized animation
  SkeletonAnim.Start();
end;

Skeleton Animation Control

// Start all joint animations together
SkeletonAnim.Start();

// Stop all
SkeletonAnim.Stop();

// Reset to first frame
SkeletonAnim.Reset();

// Adjust speed for all joints
SkeletonAnim.SetSpeed(0.5);  // Half speed

// Access individual interpolators
for var Interpolator in SkeletonAnim.Interpolators do
begin
  ShowMessage(Interpolator.PropertyName);
end;

AutoRepaint

The AutoRepaint property controls viewport updates:

// Automatic viewport repaint (default)
SkeletonAnim.AutoRepaint := True;

// Manual control for better performance
SkeletonAnim.AutoRepaint := False;
GorillaViewport1.BeginUpdate();
try
  SkeletonAnim.Start();
  // ... perform other operations
finally
  GorillaViewport1.EndUpdate();
end;

Vertex Animation

Vertex (or mesh) animation directly modifies mesh vertices over time, useful for organic deformations and morph targets.

TCoordinateKeyAnimation

var
  Anim: TCoordinateKeyAnimation;
  Key: TCoordinateKey;
  Vertices: TPoint3DDynArray;
begin
  Anim := TCoordinateKeyAnimation.Create(Self);
  Anim.PropertyName := 'Data.Vertices';
  Anim.Duration := 2.0;
  Anim.Loop := True;
  Anim.AddElement(CustomMesh1, True);

  // Key 0: Original vertices
  Key := TCoordinateKey(Anim.Keys.Add);
  Key.Time := 0.0;
  SetLength(Vertices, 8);
  Vertices[0] := Point3D(-1, -1, -1);
  Vertices[1] := Point3D( 1, -1, -1);
  // ... set all vertices
  Key.Vertices[CustomMesh1] := Vertices;

  // Key 1: Deformed vertices
  Key := TCoordinateKey(Anim.Keys.Add);
  Key.Time := 1.0;
  Vertices[0] := Point3D(-1.5, -1, -1);
  Vertices[1] := Point3D( 1.5, -1, -1);
  // ... set deformed vertices
  Key.Vertices[CustomMesh1] := Vertices;

  Anim.Start();
end;

Loading Animations from Files

Animations are typically imported from 3D model files (G3D, DAE or FBX) using animation definitions.

It is not a recommended process, but good for understanding the structures behind.

var
  Loader: TGorillaLoader;
  ModelDef: TModelDef;
  AnimDef: TAnimationDef;
  Animation: TGorillaAnimation;
begin
  Loader := TGorillaLoader.Create();
  try
    // Load model with animations
    ModelDef := Loader.LoadUndefinedModelDefFromFile(nil, 'character.fbx');

    // You need to setup FMX models and meshes, otherwise LoadFromAnimationDef
    // may find references objects not.

    // Iterate through embedded animations
    for AnimDef in ModelDef.Animations do
    begin
      Animation := TGorillaAnimation.CreateEx(AnimationManager1);
      Animation.LoadFromAnimationDef(AnimDef);

      // Add to manager
      AnimationManager1.AddAnimation(AnimDef.Id, Animation);
    end;
  finally
    Loader.Free();
  end;
end;

Animation Transformation

Transform animations for mirroring or custom modifications:

var
  MirrorMatrix: TMatrix3D;
begin
  // Create mirror matrix (flip on X axis)
  MirrorMatrix := TMatrix3D.CreateScaling(Point3D(-1, 1, 1));

  // Transform all keys in animation
  Animation.Skeleton.Transform(MirrorMatrix);
end;

Animation Caching

For performance optimization, Gorilla3D can cache animated frames:

Frame Caching

// Enable caching during import
Animation.LoadFromAnimationDef(AnimDef);

// Get cached frame for rendering
var
  MeshBuffer: TMeshBufferObject;
begin
  MeshBuffer := Animation.GetCurrentCachedFrame(MeshDef);
  if Assigned(MeshBuffer) then
  begin
    // Render cached frame
  end;
end;

Fixed Frame Debugging

// Set specific frame for debugging
Animation.SetFixedCacheFrame(15);  // Show frame 15

// Release fixed frame
Animation.UnsetFixedCacheFrame();

Frame Information

// Get animation frame info
ShowMessage(Format('Frames: %d, FPS: %d', [
  Animation.FrameCount,
  Animation.FrameRate
]));

Re-Baking and Discarding Cached Frames

Cached frames can be baked again or dropped at runtime, for all animations or by id:

// re-bake all animations with the default flags
GorillaModel1.RecacheAnimations(GORILLA_ANIMATION_CACHING_DEFAULT);

// re-bake only selected animations, drop the cache of others
GorillaModel1.RecacheAnimationsByName(['walk', 'run']);
GorillaModel1.DiscardAnimationCacheByName(['idle']);

Animations without cached frames are skinned on the CPU. See Re-Baking or Dropping the Cache for the details.

Note: TAnimationCachingFlag.Compressed is not supported on Vulkan. A one-time warning is logged and the bind pose is shown.

Cached Frames and In-Place Playback

Cached frames hold baked vertex positions, so anything that changes the pose of a clip invalidates them. Removing the root motion does exactly that: InPlace drops the frames and leaves them dropped, and a skinned mesh whose frames are gone is drawn from its static buffer - the bind pose - while the animation still reports IsRunning = True.

// clip was loaded with caching flags
Animation.SetInPlace(True, True);   // take the travel out AND bake the clip again

Assigning Animation.InPlace := True keeps the old behaviour and does not rebuild. An uncached clip is skinned live and needs neither. See Root Motion and In-Place Playback.

Force Stepping

Force animation updates outside the normal FMX message loop for smoother playback:

// In your main rendering loop or timer
if TGorillaAnimationManager.ForceStep(0.01) then
  GorillaViewport1.EndUpdate()
else
  GorillaViewport1.EndUpdateWithoutInvalidate();

Parameters:

  • AMinDeltaTime: Minimum time (seconds) since last forced update (default: 0.01)

Returns: True if step was forced and viewport needs updating

Delphi 13+: FMX has no animation thread left to step, so ForceStep only reports whether AMinDeltaTime has passed - it does not advance anything. Skeleton animations are driven by TGorillaRenderClock instead, which TGorillaViewport ticks at the start of every rendered frame. Poses and image stay in step without any call on your side; existing code that uses the result as a rate gate keeps working.

Animation Events

React to animation progress:

procedure TForm1.AnimationProcess(Sender: TObject);
begin
  // Called on each animation frame
  ProgressBar1.Value := Animation.Skeleton.NormalizedTime * 100;
end;

procedure TForm1.AnimationFinish(Sender: TObject);
begin
  // Called when animation completes
  ShowMessage('Animation finished');
end;

// Assign events
Animation.Skeleton.OnProcess := AnimationProcess;
Animation.Skeleton.OnFinish := AnimationFinish;

Simple Property Animation

For simple property animations without keyframes, use TPoint3DAnimation:

var
  Anim: TPoint3DAnimation;
begin
  Anim := TPoint3DAnimation.Create(Self);
  Anim.Parent := Cube1;
  Anim.PropertyName := 'Position.Point';
  Anim.StartValue.Point := Point3D(0, 0, 0);
  Anim.StopValue.Point := Point3D(10, 0, 0);
  Anim.Duration := 2.0;
  Anim.StartFromCurrent := True;
  Anim.Start();
end;

Best Practices

  1. Use Skeleton Animation for Characters: Group related joint animations in TSkeletonKeyAnimation for synchronized playback

  2. Cache Complex Animations: Enable frame caching for CPU-intensive vertex animations

  3. Control AutoRepaint: Disable AutoRepaint and manually control viewport updates for better performance

  4. Use Quaternions for Rotation: TQuaternion3DKeyAnimation provides smoother rotation than Euler angles

  5. Optimize Keyframe Count: Use only necessary keyframes; interpolation handles in-between frames

  6. Force Stepping for Smoothness: Up to Delphi 12, use ForceStep() in rendering loops to avoid FMX timer jitter (Delphi 13+ does this through TGorillaRenderClock)

  7. Check Animation State: Always verify IsRunning before operations that depend on active animation

  8. Proper Cleanup: Always stop animations before destroying animated objects

  9. Use Animation Manager: Centralize animation control through TGorillaAnimationManager and switch clips with PlayAnimation to get crossfades

  10. Use Sorted Lists: Use GetAnimationNames() / GetSortedAnimations() instead of enumerating the Animations hashmap whenever order matters

  11. Test Playback Speed: Adjust animation speed based on target platform performance

Common Patterns

Continuous Rotation

procedure CreateRotationAnimation(AObject: TControl3D);
var
  Anim: TPoint3DKeyAnimation;
  Key: TPoint3DKey;
begin
  Anim := TPoint3DKeyAnimation.Create(AObject);
  Anim.PropertyName := 'RotationAngle.Point';
  Anim.Duration := 4.0;
  Anim.Loop := True;
  Anim.Interpolation := TInterpolationType.Linear;

  Key := TPoint3DKey(Anim.Keys.Add);
  Key.Time := 0.0;
  Key.Value[AObject] := Point3D(0, 0, 0);

  Key := TPoint3DKey(Anim.Keys.Add);
  Key.Time := 1.0;
  Key.Value[AObject] := Point3D(0, 360, 0);

  Anim.Start();
end;

Bounce Effect

Anim := TPoint3DKeyAnimation.Create(Self);
Anim.PropertyName := 'Position.Point';
Anim.Interpolation := TInterpolationType.Bounce;
Anim.AnimationType := TAnimationType.Out;
Anim.Duration := 1.0;
// ... add keys
Anim.Start();

Ping-Pong Animation

Anim := TPoint3DKeyAnimation.Create(Self);
Anim.Loop := True;
Anim.AutoReverse := True;  // Plays forward then backward
// ... configure and start

Troubleshooting

Animation Not Playing

// Check animation is enabled
if not Animation.Skeleton.Enabled then
  Animation.Skeleton.Enabled := True;

// Verify parent is set
if not Assigned(Animation.Parent) then
  Animation.Parent := SomeContainer;

// Check duration is set
if Animation.Skeleton.Duration = 0 then
  Animation.Skeleton.Duration := 2.0;

Jerky Playback

// Up to Delphi 12: use ForceStep for smoother updates
// (Delphi 13+ steps animations per rendered frame automatically)
TGorillaAnimationManager.ForceStep(0.01);

// Or adjust interpolation
Animation.Skeleton.Interpolation := TInterpolationType.Cubic;

Animation Too Fast/Slow

// SetSpeed scales the interpolator DURATIONS (relative, cumulative)
Animation.SetSpeed(2.0);  // twice as long -> half speed
Animation.SetSpeed(0.5);  // half as long  -> double speed

For an absolute, repeatable rate see An Absolute Playback Rate.

Wrong Animation Order in a List

// Do not enumerate the hashmap - its order is arbitrary
for var LName in Manager.GetAnimationNames() do
  ListBox1.Items.Add(LName);

Memory Issues with Vertex Animation

// Enable caching to reduce real-time computation
// Ensure proper cleanup of cached frames

See Also