Skip to content

Physics-ready avatars: colliders, joint limits and ragdolls

Every avatar can hand itself to the host's physics engine as a ragdoll: one rigid body per bone, a capsule or a box on each fitted to the avatar's own skinned mesh (its height, weight and outfit), and a joint from each body to its parent whose limits agree with the IK's. The description is plain data any engine takes (Jolt, PhysX, Bullet, Godot, Unity, Unreal). Then the handoff runs both ways: the current pose and its velocities go into the host's bodies when it takes over, the host's simulated bodies come back onto the avatar every frame (it draws the ragdoll, fingers, face and clothes included), and a blend takes the last ragdoll pose back into a clip for getting up.

The public API is seven functions and four structs (C reference: ragdolls). The options and the info start with size; sona_ragdoll_defaults sets every field of the options.

Quick start

sona_ragdoll_body bodies[SONA_RAGDOLL_BODIES];
sona_ragdoll_options o;
sona_ragdoll_defaults(&o);
/* most engines build a ragdoll at its rest pose */
o.flags = SONA_RAGDOLL_REST_POSE;
sona_avatar_ragdoll(avatar, &o, bodies, SONA_RAGDOLL_BODIES, NULL);
/* shapes, masses, joints: see "Into an engine" */
my_engine_build_ragdoll(bodies);

/* the moment it goes limp: where every body is and how fast it moves */
sona_ragdoll_state now[SONA_RAGDOLL_BODIES];
sona_avatar_ragdoll_state(avatar, now, SONA_RAGDOLL_BODIES, NULL);
my_engine_set_pose_and_velocities(now);

/* every frame, after the physics step */
/* world position and rotation per body */
my_engine_read_bodies(now);
sona_avatar_ragdoll_drive(avatar, now, SONA_RAGDOLL_BODIES, 1.0f, 0);
/* the avatar draws the ragdoll */
sona_update(ctx, dt, &view, NULL);

/* getting up */
sona_ragdoll_info info = { sizeof info };
/* face up or down, where, which way to face */
sona_avatar_ragdoll_info(avatar, &info);
sona_placement p = { { info.getup_position[0], ground_y,
    info.getup_position[2] }, info.getup_turn_deg, 1 };
sona_avatar_move(avatar, &p, 0);
/* the stock get-up clips */
sona_avatar_play(avatar, info.face_up ? "getup_back" : "getup_front", NULL);
/* the lying pose blends into the clip over 0.6 s */
sona_avatar_ragdoll_release(avatar, 0.6f);
sona_ragdoll_body bodies[SONA_RAGDOLL_BODIES];
sona_ragdoll_options o;
sona_ragdoll_defaults(&o);
// most engines build a ragdoll at its rest pose
o.flags = SONA_RAGDOLL_REST_POSE;
sona_avatar_ragdoll(avatar.raw(), &o, bodies, SONA_RAGDOLL_BODIES, nullptr);
my_engine_build_ragdoll(bodies, SONA_RAGDOLL_BODIES);
// shapes, masses, joints: see "Into an engine"

// the moment it goes limp: where every body is and how fast it moves
sona_ragdoll_state now[SONA_RAGDOLL_BODIES];
sona_avatar_ragdoll_state(avatar.raw(), now, SONA_RAGDOLL_BODIES, nullptr);
my_engine_set_pose_and_velocities(now, SONA_RAGDOLL_BODIES);

// every frame, after the physics step
// world position and rotation per body
my_engine_read_bodies(now, SONA_RAGDOLL_BODIES);
sona_avatar_ragdoll_drive(avatar.raw(), now, SONA_RAGDOLL_BODIES, 1.0f, 0);
// the avatar draws the ragdoll
ctx.update(dt, &view);

// getting up
sona_ragdoll_info info = { (uint32_t)sizeof info };
// face up or down, where, which way to face
sona_avatar_ragdoll_info(avatar.raw(), &info);
const sona_placement p = { { info.getup_position[0], ground_y,
    info.getup_position[2] }, info.getup_turn_deg, 1 };
avatar.move(p);
// the stock get-up clips
avatar.play(info.face_up ? "getup_back" : "getup_front");
// the lying pose blends into the clip over 0.6 s
sona_avatar_ragdoll_release(avatar.raw(), 0.6f);
var o = SonaAvatar.RagdollDefaults();
// most engines build a ragdoll at its rest pose
o.flags = Native.SONA_RAGDOLL_REST_POSE;
var bodies = avatar.Ragdoll(o);
// shapes, masses, joints: see "Into an engine"
MyEngineBuildRagdoll(bodies);

// the moment it goes limp: where every body is and how fast it moves
var now = new Native.sona_ragdoll_state[Native.SONA_RAGDOLL_BODIES];
avatar.TryGetRagdollState(now);
MyEngineSetPoseAndVelocities(now);

// every frame, after the physics step
// world position and rotation per body
MyEngineReadBodies(now);
avatar.RagdollDrive(now);
// the avatar draws the ragdoll
ctx.Update(dt, view);

// getting up
// face up or down, where, which way to face
if (avatar.TryGetRagdollInfo(out var info))
{
    avatar.Move(new SonaPlacement(info.getup_position[0], groundY,
        info.getup_position[2], info.getup_turn_deg));
    // the stock get-up clips
    avatar.Play(info.face_up != 0 ? "getup_back" : "getup_front");
    // the lying pose blends into the clip over 0.6 s
    avatar.RagdollRelease(0.6f);
}
let mut o = ragdoll_defaults();
// most engines build a ragdoll at its rest pose
o.flags = sona_sys::SONA_RAGDOLL_REST_POSE;
let bodies = avatar.ragdoll(Some(&o))?;
// shapes, masses, joints: see "Into an engine"
my_engine_build_ragdoll(&bodies);

// the moment it goes limp: where every body is and how fast it moves
let mut now = avatar.ragdoll_state()?;
my_engine_set_pose_and_velocities(&now);

// every frame, after the physics step
// world position and rotation per body
my_engine_read_bodies(&mut now);
avatar.ragdoll_drive(Some(&now), 1.0, 0)?;
// the avatar draws the ragdoll
ctx.frame()?.update(dt, Some(view))?;

// getting up
// face up or down, where, which way to face
let info = avatar.ragdoll_info()?;
let p = info.getup_position;
avatar.move_to(&Placement { position: [p[0], ground_y, p[2]],
    turn_deg: info.getup_turn_deg, scale: 1.0 }, 0.0);
// the stock get-up clips
let clip = if info.face_up != 0 { "getup_back" } else { "getup_front" };
avatar.play(clip, &PlayOptions::default())?;
// the lying pose blends into the clip over 0.6 s
avatar.ragdoll_release(0.6)?;
# most engines build a ragdoll at its rest pose
bodies = avatar.ragdoll(rest_pose=True)
# shapes, masses, joints: see "Into an engine"
my_engine_build_ragdoll(bodies)

# the moment it goes limp: where every body is and how fast it moves
now = avatar.ragdoll_state()
my_engine_set_pose_and_velocities(now)

# every frame, after the physics step
# world position and rotation per body
my_engine_read_bodies(now)
avatar.ragdoll_drive(now)
# the avatar draws the ragdoll
ctx.update(dt, view)

# getting up
# face up or down, where, which way to face
info = avatar.ragdoll_info()
x, _, z = info["getup_position"]
avatar.move((x, ground_y, z), turn_deg=info["getup_turn_deg"])
# the stock get-up clips
avatar.play("getup_back" if info["face_up"] else "getup_front")
# the lying pose blends into the clip over 0.6 s
avatar.ragdoll_release(0.6)

samples/physics/ragdoll_jolt.cpp is all of this with Jolt Physics, start to finish.

The bodies

Sixteen, in this order (the index is what parent and no_collide count in):

# Joint (parent) Shape; joint to the parent; limits from
0 Hips capsule across
1 Spine (0) capsule across; swing-twist; the defaults below
2 Chest (1) capsule across; swing-twist; the defaults below
3 Head (2) capsule upright; swing-twist; the look-at's defaults: yaw 70, up 35, down 45
4, 7 Left, RightUpperArm (2) capsule along the bone; swing-twist; shoulder_back_deg, shoulder_across_deg
5, 8 Left, RightLowerArm (4, 7) capsule along the bone; hinge; elbow_max_deg
6, 9 Left, RightHand (5, 8) box; swing-twist; wrist_swing_deg, wrist_twist_deg
10, 13 Left, RightUpperLeg (0) capsule along the bone; swing-twist; hip_forward_deg, hip_back_deg, hip_out_deg, hip_in_deg
11, 14 Left, RightLowerLeg (10, 13) capsule along the bone; hinge; knee_max_deg
12, 15 Left, RightFoot (11, 14) box, flat on the sole; swing-twist; ankle_swing_deg, ankle_twist_deg

Every other joint rides on its nearest body: the neck and shoulders on the chest, fingers and held props on the hands, toes on the feet, the face and the body-shape joints on theirs. When the host drives the bodies, those joints keep the clip's pose relative to their body, so fingers still curl and faces still talk on a ragdoll.

A body's frame is its joint's: the origin at the joint, the axes the joint's own with the scale taken out. That is the frame every engine puts a ragdoll body at (Unity's bone transform, Unreal's physics-asset body, Godot's PhysicalBone3D); the shape sits inside it at shape_position and shape_rotation.

The shapes

Each vertex of the body meshes (not held props) belongs to the body of its strongest joint. The vertices are skinned at the rest pose of this avatar's own rig, so a tall avatar gets longer legs and a heavy one wider thighs, and its clothes are part of the shape: a big coat makes a big chest. Then per body:

  • A capsule lies along the bone (arms and legs), across the body (hips, spine, chest, so a ragdoll rolls the way a person does) or upright (the head with its hair or hat). It is centred on the middle of the cross-section, its radius holds coverage (0.9) of the vertices, and of the lengths from "the caps inside the extent" to "the straight part over the whole extent" it takes the one of least volume that still holds coverage.
  • A box (hands and feet; capsules with SONA_RAGDOLL_ALL_CAPSULES) lies along the bone or, for a foot, along the foot on the ground with its bottom on the sole, and spans the vertices between the tails on each axis (a threshold of 2%).

A body with no mesh (fewer than 8 vertices) gets a capsule from the bone itself. A capsule's axis is its local Y, as in Jolt, PhysX (after a 90 degree turn: PhysX capsules lie along X), Godot and Unity (direction = 1). half_height is half the straight part, radius the radius: Unity's height is 2 * (half_height + radius).

Mass

total_mass 0 (the default): a person of this avatar's height (the crown about 0.25 m above the head joint, the soles 0.03 m below the ankles, as sona_avatar_capsule has them) at a body mass index of 22, from 17 at the thinnest to 32 at the heaviest weight, times the placement's scale cubed: about 50 to 90 kg for the cast. It is shared out as a person's is (Winter, Biomechanics and Motor Control of Human Movement, table 4.1), in shares set to 14.2%, 13.9%, 21.6%, 8.1%, 2.8%, 1.6%, 0.6%, 10%, 4.65% and 1.45% for the pelvis, abdomen, thorax, head and neck, upper arm, forearm, hand, thigh, shank and foot. A given total_mass is shared the same way. Inertia is the engine's, from the shapes.

Collisions inside the ragdoll

no_collide has a bit per body this one should not collide with: its parent and its children, and every body its shape already overlaps at the rest pose (the hips and the thighs, the chest and the upper arms). Feed it to the engine's group filter (Jolt's GroupFilterTable::DisableCollision, PhysX's PxSetGroupCollisionFlag or a filter shader, Bullet's setIgnoreCollisionCheck, Godot's add_collision_exception_with, Unity's Physics.IgnoreCollision, Unreal's physics-asset collision pairs). Without it, overlapping shapes push the ragdoll apart the moment it starts.

The joints and their limits

Each body but the hips has a joint to its parent at its own origin (pivot is that point in the parent's frame). The joint's frame is given twice, in the parent's frame (frame_parent) and in this body's (frame_child); at the rest pose the two are the same frame in the world. Its X is the twist axis, along the bone. The limits are the child's frame turned from the parent's, read as a twist about X, then a swing about Y (positive turns X towards -Z) and Z (positive turns X towards +Y), each between its min and max:

  • Hinges (elbows, knees) turn about Z only, from 0 (straight) to elbow_max_deg or knee_max_deg. Positive is the way the IK bends them: an elbow brings the hand forward, a knee takes the foot back.
  • Swing-twist joints have asymmetric ranges where a person does. The hip swings from hip_back_deg behind to hip_forward_deg in front of hanging straight down, and from hip_in_deg across to hip_out_deg out to the side; the shoulder from shoulder_back_deg behind the arm held out level to 90 + shoulder_across_deg across the chest, and as far up and down. These are the IK's own limits measured on the IK's own axes (the parent's rest axes), so a ragdoll goes where the IK lets a limb go and no further:
  • Engines whose cones are symmetric (Jolt's SwingTwistConstraint, PhysX's spherical joint, Unity's CharacterJoint, Godot's cone twist, Unreal's constraint profile) take cone_frame in place of frame_parent: the parent's frame turned to the middle of both swing ranges, with half angles cone_y and cone_z. Those cones are elliptical, so they round off the corners of the asymmetric ranges; engines with per-axis limits (PhysX's D6 with a pyramid limit, Jolt's SixDOFConstraint, Bullet's btGeneric6DofSpring2Constraint, Godot's 6DOF joint) take frame_parent and the min and max as they are.

Joints the IK does not limit take these defaults (degrees): spine and chest twist 15 and 20 either way, bend 30 forward and 15 back, 15 to each side; head roll 30; upper arm twist 70; thigh twist 35. The limits come from the avatar's IK limits (sona_avatar_ik_limits), or from limits in the options.

Into an engine

  • Jolt. Body: position, rotation. Shape: RotatedTranslatedShape of a CapsuleShape(half_height, radius) or BoxShape(half_extents). Joint frames: world space at the rest pose: mTwistAxis = frame X, mPlaneAxis = frame Z. Swing and twist: mPlaneHalfConeAngle = cone_y, mNormalHalfConeAngle = cone_z (Jolt's normal axis is plane x twist, our Y); hinge: mHingeAxis = frame Z, mNormalAxis = frame X, mLimitsMin/Max = swing_z_min/max.
  • PhysX. Body: PxTransform. Shape: PxCapsuleGeometry(radius, half_height) turned 90 degrees about Z (PhysX capsules lie along X), local pose from the shape fields. Joint frames: PxD6Joint local frames from pivot + frame_parent, and the origin + frame_child. Swing and twist: twist X, swing1 Y, swing2 Z: PxJointLimitPyramid(swing_y_min, swing_y_max, swing_z_min, swing_z_max), PxJointAngularLimitPair(twist_min, twist_max).
  • Bullet. Body: btTransform. Shape: btCapsuleShape(radius, 2 * half_height) (Y) in a btCompoundShape. Joint frames: btGeneric6DofSpring2Constraint frames A and B. Swing and twist: angular lower and upper limits: X twist, Y, Z the swings.
  • Godot 4. Body: PhysicalBone3D on the joint. Shape: CapsuleShape3D (height 2 * (half_height + radius)), body_offset from the shape fields. Joint frames: joint_type 6DOF, joint_rotation from frame_child. Swing and twist: the 6DOF angular limits per axis.
  • Unity. Body: the bone's Rigidbody. Shape: CapsuleCollider (center, radius, height, direction 1). Joint frames: ConfigurableJoint: axis = frame X, secondaryAxis = frame Y. Swing and twist: lowAngularXLimit/highAngularXLimit = twist, angularYLimit = cone_y, angularZLimit = cone_z (on cone_frame).
  • Unreal. Body: physics-asset body on the bone. Shape: FKSphylElem (Unreal's capsules lie along Z: turn the shape). Joint frames: the constraint's frames. Swing and twist: Swing1, Swing2 = cone, Twist.

Coordinates are the SDK's world (as sona_joint_world gives it: Y up, metres, avatars facing -Z at turn 0 with their left at +X). An engine that mirrors it, as the host already does for the avatar's meshes, negates z in positions and takes quaternions as (-x, -y, z, w); Unreal also swaps to Z up and centimetres.

The handoff

Into the engine. sona_avatar_ragdoll_state gives every body's world position and rotation at the last pose, and its velocity and angular velocity from the last two poses (on the scene clock, the sum of sona_update's dt). The history starts when sona_avatar_ragdoll is called; until a second pose the velocities are zero. A running avatar keeps its momentum when it goes limp. The pose history is kept only for avatars with a ragdoll; poses are not forced while it only tracks, so an avatar posed less often (a small one in a crowd) gives velocities over the time between its poses.

Back onto the avatar. sona_avatar_ragdoll_drive(a, bodies, 16, weight, flags) after each physics step: from the next pose the avatar is drawn in the host's bodies, and it is posed every frame while driven. Between the bodies every joint keeps the clip's pose relative to its body. weight below 1 blends from the clip's pose, body by body down the hierarchy (the hips' position and turn, then each body's turn relative to its parent and its offset from it), so limbs never come apart: 0.2 to 0.5 gives a hit reaction on a playing clip, 1 the full ragdoll. A solver lets joints stretch a little under load; SONA_RAGDOLL_KEEP_LENGTHS takes only the turns and the hips' position, so every bone keeps its length. Velocities in the array are not read. NULL bodies stop driving at once.

The placement still places the avatar (it is what moves the culling sphere and where a clip plays next), but it no longer moves a driven ragdoll: the bodies are world positions. Keep the placement near the hips while the ragdoll travels if the avatar may be culled.

Getting up. sona_avatar_ragdoll_info says whether the avatar lies on its back (face_up 1), on its front (0) or is upright (-1), where its hips are, the lowest point of any shape, and a placement to get up from: over the hips, turned to face its feet on its back (people sit up towards their feet) or its head on its front (they push up and stand facing that way). Move the placement there, play a get-up clip that starts lying down, and call sona_avatar_ragdoll_release(a, seconds): the last drawn ragdoll pose stays where it is in the world and blends into the clip over seconds (smoothstep), body by body as above, then the avatar is back on its clip, bit for bit. release(a, 0) cuts. The stock clips "getup_back" and "getup_front" do this (below, "Getting up"); a clip of your own works the same, imported with sona_clip_import and played by its key.

sona_avatar_ragdoll_clear drops the ragdoll at once: no history, no drive, no blend.

Getting up

Two stock clips get a ragdoll back on its feet: "getup_back" rises from lying on the back with the feet towards -Z, "getup_front" from lying face down with the head towards -Z, as sona_ragdoll_info's getup_turn_deg places them. Each is played by its key like any clip (sona_avatar_play(a, "getup_back", &po), loop 0) and is made the first time it is asked for, on the ctx's rig, so the hips' heights fit any body: lying, sitting up, knees up, a crouch over the feet, rising, standing, with the feet on the floor wherever they bear weight (clips with lengths set to 2.55 and 2.8 s at a frame rate of 30 fps, the last pose held). To get up: read face_up, move the placement to getup_position and getup_turn_deg, play the clip and call sona_avatar_ragdoll_release(a, 0.4f); the blend carries the ragdoll's pose into the clip's first frame.

Powered ragdolls

The host's physics can drive its joint motors to the clip: sona_avatar_ragdoll_motors(a, out, cap, &count) gives, per body in sona_avatar_ragdoll's order, the pose the avatar's clip, layers and IK give it now, whatever the host's bodies are doing:

Field What
rotation the body's turn in its parent body's frame (q_parent^-1 * q_body); the hips: their world turn
joint_rotation the same in the joint's frame, frame_parent to frame_child: the identity at the rest pose; a Jolt swing-twist motor target or a PhysX D6 drive target as it stands
angular_velocity the rate of rotation, radians a second, in the parent body's frame
world_position, world_rotation, velocity, world_angular_velocity the body as the clip has it, for a root drive or a blend

Velocities come from the last two poses (zero until there are two). A typical loop: drive the host's bodies with sona_avatar_ragdoll_drive (the avatar draws them), and each step set every constraint's motor target to joint_rotation, with stiffness to taste: the body tries to do the clip while it falls.

Determinism and threads

The fitting and the handoff are double maths with the core's own trig, no FMA contraction. The same avatar and options give the same bodies to the bit; driven and blending avatars give the same palettes on 0 and 4 worker threads. The handoff runs on the posing threads, each avatar's state touched only by the thread posing it; calls are made on the owner thread between updates.

Cost

Nothing for avatars without a ragdoll: the pose and the posing schedule test one pointer. With one, each pose records 16 world transforms; driving adds a blend of 16 bodies and one 3x4 multiply per joint. sona_avatar_ragdoll (the fit) skins the body meshes once at rest and sorts each body's vertices: a few milliseconds per avatar, on the owner thread, so call it when an avatar is added or changes clothes, not every frame.

The sample

samples/physics/ragdoll_jolt.cpp (target ragdoll_jolt, C++17, built with -DSONA_WITH_JOLT=ON, which fetches Jolt Physics 5.5.0 at a pinned hash into the third-party cache and builds it beside the sample only; it is not part of the library). An avatar stands at the top of six steps, trips (its pose and velocities go into a Jolt ragdoll built from the bodies at the rest pose, plus a push), falls down them, lies still and gets up from its front, or with --backwards from its back. It renders headless on the best GPU (sona_headless_open), ray-casts the same boxes Jolt collides with for the stairs, and writes:

  • <out>-colliders.png: the shapes over the mesh, standing,
  • <out>-fall.png: eight moments of the fall (the last with the shapes over the lying body),
  • <out>-getup.png: four moments of getting up,
  • <out>-getup-front.bvh, <out>-getup-back.bvh: the get-up clips it imports.

It fails when a drawn body joint leaves its Jolt body by more than 1 mm, a hinge bends more than 11 degrees the wrong way or any joint goes 14 degrees past its limits (Jolt's limits are soft for a frame of an impact), the avatar does not fall, or it does not end on its feet. Jolt runs single-threaded with its cross-platform determinism on, so the fall is the same every run.

ragdoll_jolt --cast devs-cast.json --size 640x360 --out ragdoll
    [--backwards]

Limits

  • Balance is the host's: the motor targets follow the clip, but keeping a powered ragdoll upright (a balance controller) is the engine's.
  • No soft parts: hair and cloth sway is a separate, optional capability.
  • The shapes are fitted once at the rest pose: a long skirt makes the thighs' capsules wide but does not swing.

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