Skip to content

Bring your own animation

Play your own clips on any avatar: glTF 2.0 (.gltf, .glb), FBX (binary and ASCII, 6.x and 7.x) and BVH. The SDK reads the file, matches its bones to the avatar's joints by name, retargets one take onto the avatar rig and keeps it in the context under a key. From then on the key works everywhere a stock clip key does: sona_avatar_play, sona_avatar_crossfade, sona_avatar_queue, sona_add_options.clip, clip events, marks, footfalls and root motion. Mixamo downloads, motion capture (BVH from capture libraries) and hand-keyed clips from Blender, Maya, 3ds Max, Unity or Unreal all go through the same path.

sona_import_options o;
sona_import_info info;
sona_anim_file *f;
char why[256];

sona_import_defaults(&o);
/* NULL: the take's own name */
o.key = "wave_big";
if (sona_anim_file_open("wave.fbx", &o, &f, why,
    sizeof why) != SONA_OK) { puts(why); return; }
/* waits for the rig data, read through the sources */
while (sona_clip_import(ctx, f, &o, &info) == SONA_PENDING)
  sona_update(ctx, 1.0 / 60, &view, NULL);
/* the clip is kept; the file is not needed any more */
sona_anim_file_free(f);

sona_avatar_crossfade(avatar, "wave_big", NULL, 0.25f);
sona_import_options o;
sona_import_info info;
sona_anim_file *f = nullptr;
char why[256];

sona_import_defaults(&o);
// nullptr: the take's own name
o.key = "wave_big";
if (sona_anim_file_open("wave.fbx", &o, &f, why,
    sizeof why) != SONA_OK) { std::puts(why); return; }
// waits for the rig data, read through the sources
while (sona_clip_import(ctx.raw(), f, &o, &info) == SONA_PENDING)
  ctx.update(1.0 / 60, &view);
// the clip is kept; the file is not needed any more
sona_anim_file_free(f);

avatar.crossfade("wave_big", 0.25f);
// the binding has no import wrapper: the calls of its raw Native layer
var o = new Native.sona_import_options();
var info = new Native.sona_import_info();
IntPtr f;
Native.sona_import_defaults(&o);
// null: the take's own name
var key = System.Text.Encoding.UTF8.GetBytes("wave_big\0");
var path = System.Text.Encoding.UTF8.GetBytes("wave.fbx\0");
var why = new byte[256];
fixed (byte* k = key) fixed (byte* p = path) fixed (byte* w = why)
{
    o.key = (IntPtr)k;
    if (Native.sona_anim_file_open(p, &o, &f, w,
        (UIntPtr)why.Length) != SonaResult.Ok) return;
    // waits for the rig data
    while (Native.sona_clip_import(ctx.Handle, f, &o,
        &info) == SonaResult.Pending)
        ctx.Update(1.0 / 60);
}
// the clip is kept; the file is not needed any more
Native.sona_anim_file_free(f);

avatar.Crossfade("wave_big", 0.25f);
// the crate has no import wrapper: the C calls through sona_sys
let mut o: sona_sys::sona_import_options = unsafe { std::mem::zeroed() };
let mut info: sona_sys::sona_import_info = unsafe { std::mem::zeroed() };
let mut f: *mut sona_sys::sona_anim_file = std::ptr::null_mut();
let mut why = [0 as std::ffi::c_char; 256];
unsafe {
    sona_sys::sona_import_defaults(&mut o);
    // null: the take's own name
    o.key = c"wave_big".as_ptr();
    if sona_sys::sona_anim_file_open(c"wave.fbx".as_ptr(), &o, &mut f,
        why.as_mut_ptr(), why.len()) != sona_sys::SONA_OK {
        return Ok(());
    }
    // waits for the rig data
    while sona_sys::sona_clip_import(ctx.raw(), f, &o,
        &mut info) == sona_sys::SONA_PENDING {
        sona_sys::sona_update(ctx.raw(), 1.0 / 60.0, std::ptr::null(),
            std::ptr::null_mut());
    }
    // the clip is kept; the file is not needed any more
    sona_sys::sona_anim_file_free(f);
}
avatar.crossfade("wave_big", &PlayOptions::default(), 0.25)?;
anim = sona.AnimFile(path="wave.fbx")
# None: the take's own name; waits for the rig data
ctx.import_clip(anim, key="wave_big")
# the clip is kept; the file is not needed any more
anim.close()

avatar.crossfade("wave_big", 0.25)

The sample samples/c/import_clip_vk.c does all of this and draws a contact sheet:

import_clip_vk --clip walk.bvh [--take name] [--key name] [--map
    Source=Joint ...]
               [--rest bind|nodes|first] [--frames 8] [--travel] [--out
                   import-clip.png]

It prints every take, every bone that drives a joint, and what the import found (frames, rate, naming, joints driven, the hips' travel scale).

1. The API

All of it is in the C reference: imported clips. Structs carry a size field (sona_import_defaults sets it); the info struct is filled whole.

Call What
sona_import_defaults(o) zeroed options with size set
sona_import_formats() bit 1 << SONA_ANIM_* for each format this build reads (BVH always; glTF and FBX unless the library was built without them)
sona_anim_file_load(bytes, len, opts, &f, why, cap) parses a file in memory; no ctx. SONA_E_CORRUPT, _UNSUPPORTED, _LIMIT with the reason in why
sona_anim_file_open(path, ...) the same from a path; a .gltf's external buffers are read beside it
sona_anim_file_takes, _take(f, i, &seconds) the takes: glTF animations, FBX animation stacks, the one BVH motion (named after the file)
sona_anim_file_bones, _bone(f, i, &parent, &joint) every bone (node), parents first, and the avatar joint it drives under the options it was loaded with
sona_clip_import(ctx, f, opts, &info) retargets one take and keeps it; SONA_PENDING until the rig data is in
sona_clip_imported_count, _get, _find(key) what the ctx holds
sona_clip_imported_remove(ctx, key) drops it; avatars playing it finish with their own reference

Options (sona_import_options):

Field Meaning
format SONA_ANIM_AUTO reads the bytes (and the extension)
key the name to play it by, up to 63 bytes. A stock clip's key, idle, still, prop or an id are refused (SONA_E_ARGUMENT). The same key again replaces the clip
take, take_index which take, by name or index
map, map_count overrides: { "source bone", "Joint" }. Source by its full name or as matched (section 2); joint by a sona_joint_find name. A NULL or empty joint leaves that bone out
fps the clip's frame rate: 0 is the file's own (BVH, FBX) or 30 (glTF), at most 240
start, end the seconds of the take to keep
root_scale metres of hips travel per source unit; 0 works it out from the legs
flags SONA_IMPORT_NO_ROOT_MOTION (the hips stay over the spot, still bobbing), _NO_TRANSLATION, _REST_BIND, _REST_NODES, _REST_FIRST_FRAME (section 3), _MAP_ONLY (no name matching), _NO_ALIGN (keep the file's facing), _NO_FINGERS, _HOLD_END (keep the last frame as a frame, for clips that don't loop)

sona_import_info reports the format, the naming that matched, bone and take counts, the joints driven, frames, rate, length, the hips' travel scale, the clip's id (it also plays it) and, per avatar joint, the source bone that drives it (joint_bone, -1 none).

An imported clip is an ordinary decoded clip inside the SDK: every frame is retargeted once at import and kept as a frame table (the stock clips build the same table on their first sample), so playing it costs what a stock clip costs. It counts in sona_stats as clip memory: 71 joints, 10 doubles each, for the channels that move; a clip 10 s long clip at a frame rate of 30 has a limit of 1.7 MB.

2. Which bone drives which joint

In order, each source bone driving at most one joint:

  1. The override map.
  2. The names. A bone's name is matched after the part before the last : or | is dropped, lower-cased, with only letters and digits kept and these prefixes removed: mixamorig (with any digits), Bip01/Bip001, CC_Base_, DEF-, J_Bip_. Each joint tries its names in a fixed order:

    Joint Names tried (Mixamo, Unity, Unreal, BVH, Biped, Blender, CC, Daz)
    Hips Hips, hip, pelvis
    Spine LowerBack, Waist, L5, spine_01, Spine, abdomenLower, abdomen
    Chest UpperChest, Spine3, Spine2, spine_05 .. spine_03, Spine02, chestUpper, Chest, T8, Spine1, chestLower
    Neck, Head Neck, neck_01, neckLower, NeckTwist01, Neck1; Head
    Shoulder lCollar, LeftCollar, clavicle_l, L Clavicle, shoulder.L, LeftShoulder
    Upper arm LeftArm, LeftUpperArm, upperarm_l, L UpperArm, upper_arm.L, lShldrBend, LeftShoulder (when a collar took the shoulder)
    Lower arm, hand LeftForeArm, LeftLowerArm, lowerarm_l, L Forearm, forearm.L, lForearmBend, LeftElbow; LeftHand, hand_l, LeftWrist
    Legs LeftUpLeg/LeftUpperLeg/thigh_l/lThighBend/LeftHip; LeftLeg/LeftLowerLeg/calf_l/lShin/LeftKnee; LeftFoot/foot_l/LeftAnkle; LeftToeBase/LeftToes/ball_l/L Toe0/lToe/LeftToe
    Fingers LeftHandIndex1..3, LeftIndexProximal/Intermediate/Distal, index_01_l..03, L Finger1/11/12, lIndex1, f_index.01.L, and the same for thumb, middle, ring, pinky (little); CMU's single LThumb

    Right-side names follow the same patterns. Any joint still free whose avatar (Unity Humanoid) name a bone has takes it. 3. Blender's numbered spine (metarig, Rigify DEF-): spine is the hips and spine.001 .. spine.006 go up to the head; the chest is the bone the shoulders hang from (spine.003), the neck the one above it, the head the last. This runs before the name table, so a Blender spine is never taken for the avatar's Spine. 4. The structure. When the neck is found, the avatar's chest is the bone right under it, and the spine is the first bone above the hips on the way there; a chest named lower down (Chest under Chest2 .. Chest4) becomes the spine. So rigs with three, four or five spine bones all work.

Bones that drive nothing are not lost: their rotation is still in the world rotations of the bones below them. Avatar joints with no bone (the body-shape helpers, fingers a file lacks) keep their rest place under their parent.

Names that a converter suffixed with the node's index (Sketchfab's glTF: mixamorig:Hips_01, CC_Base_Hip_00) are matched without it: when most of a file's bones (a threshold of 80%) end in _<digits> and no two share the digits, as an index, the suffix is dropped. A rig's own numbered bones (spine_01, index_02_l) are too few, and repeat, to count.

info.naming and sona_anim_file_bone show what happened; a rig with its own names needs a map, for example the glTF sample assets' Skeleton_torso_joint_1 to Hips.

3. The retarget

Both skeletons are put in one space. The file's space (right-handed, Y up after the FBX loader's conversion; glTF and BVH are Y up) is mirrored in Z, since the avatar rig is left-handed and faces -Z; then it is turned so the source's hips frame at rest (up: hips to head; across: right leg to left leg) lines up with the rig's (SONA_IMPORT_NO_ALIGN skips the turn). A clip authored facing +X, or a Z-up file the loader missed, still faces the camera.

For each driven joint, the clip takes its source bone's world rotation change from rest, D(t) = R(t) R(rest)⁻¹, and applies it over the rig's rest corrected to the source's rest shape: W(t) = D(t) C W_rig. C turns the rig bone's direction (joint to its next driven child) onto the source bone's direction at rest, and for the hips, the chest and the hands also turns it about that direction so the sideways axes agree (legs, shoulders, index to little finger). An A-pose source on the T-pose rig therefore plays with the arms where the source has them, and a twist that differs at rest does not twist the clip. Each joint's local rotation is then W(parent)⁻¹ W(t) (the rig's rest rotations are taken into account; they are identity on the avatar rig). Bone lengths stay the avatar's own: only the hips move.

The rest pose of the source is, by default, the bind pose for an FBX file that has one (its Pose node), and the nodes' own transforms otherwise (glTF node transforms, BVH offsets). A bind pose that puts every joint within 5 cm of where the nodes stand but turns some joint's axes about anything other than its bone is not taken: that is how Mixamo writes its FBX (the BindPose's joints point their axes along the bones, the nodes' do not, and the keys turn the nodes), and the bind would mix the two axis sets and turn whole limbs. A twist about the bone keeps the bind. SONA_IMPORT_REST_BIND takes a glTF skin's inverse bind matrices instead, SONA_IMPORT_REST_NODES forces the nodes, and SONA_IMPORT_REST_FIRST_FRAME takes the take's first frame (mocap that starts in a T-pose but whose skeleton offsets are not one).

The hips travel as the source's hips do, scaled by the legs: root_scale is the rig's hips-to-feet height over the source's at rest, so units (metres, centimetres, inches) need no setting. Sideways travel starts at zero on the first frame. Height is set where the feet touch: the lowest the source's toes (or feet) go in the take sits on the rig's toes at rest, so a capture whose root offset is arbitrary still stands on the floor; without feet, height is taken from the rest pose. sona_avatar_root_motion then works as for stock clips: EXTRACT holds the hips over the spot and hands the travel to the game, APPLY moves the avatar.

4. Formats

  • glTF 2.0 through cgltf v1.15 (MIT). Every node is a bone; skin joints and animated nodes may drive joints. Linear (slerp for rotations), step and cubic-spline samplers. Accessors are read little-endian by the SDK, so big-endian hosts read them right; normalised integer rotations are read as the spec says. Sparse animation accessors are refused. Morph weights are ignored.
  • FBX through ufbx v0.23.1 (MIT), built with UFBX_MINIMAL. Geometry is not loaded. The scene is converted to right-handed Y up in metres (UFBX_SPACE_CONVERSION_ADJUST_TRANSFORMS), so Z-up exports from Blender and 3ds Max and centimetre exports from Maya need nothing. Each animation stack is a take, over its LocalStart/LocalStop or, when those are missing, its keys' span.
  • BVH by the SDK. Channels in any order (rotations composed in channel order), position channels on any joint, scale channels. Frames are interpolated with slerp.

The limits are 512 MiB per file, 1024 bones, 256 takes, 1024 imported clips per ctx, and 11,814 frames per clip: a clip's frame table has a limit of 64 MiB (71 joints at a fixed 80 bytes a frame), which is a limit of about six and a half minutes at a frame rate of 30, and half that at 60. A longer take is refused with SONA_E_LIMIT before anything is retargeted, the message giving the frame count and the most this rate allows; import part of it (start, end, as several clips) or at a lower fps. A BVH file itself may have up to 432,000 frames.

Frames are the same on every platform: the importers and the retarget use the SDK's own fdlibm trig (as the rest of the pose path does), ufbx is built with that maths too, and glTF JSON numbers are read with the SDK's strtod (locale-free). The one libm call left is pow in ufbx's blending of FBX animation layers with partial weights.

cgltf and ufbx are fetched at configure time at pinned versions and SHA-256 hashes into SONA_THIRD_PARTY_DIR (default ~/.cache/sona-third-party, %LOCALAPPDATA%\sona-third-party on Windows). -DSONA_FETCH_THIRD_PARTY=OFF builds from that cache alone; -DSONA_WITH_GLTF_IMPORT=OFF or -DSONA_WITH_FBX_IMPORT=OFF leaves a format out, and it then answers SONA_E_UNSUPPORTED. Their notices are in native/THIRD-PARTY.txt.

This page as Markdown · All the docs as one file (llms-full.txt)