ke.animation

Skeleton hierarchies, motion clips, pose state, and skinning helpers.

Scene/render visual bridge classes are documented under kangengine.visual. The native binding may still contain implementation types for these bridges, but the public kangengine.animation module removes them. Python code should use ke.visual.ArticulationVisual or ke.visual.SkeletalVisual for viewer-side objects.

API overview

SkeletonTree

Read-only skeleton hierarchy and local bind transforms.

SkeletonMotion

Sampled skeleton animation with root motion and local rotations.

SkeletonState

Skeleton pose stored as root translation and S node rotations.

Transform

Forward-kinematics transform result.

cpu_skin

CPU-skin bind-space positions and normals.

kangengine.animation.cpu_skin(
bind_positions: npt.ArrayLike | torch.Tensor,
bind_normals: npt.ArrayLike | torch.Tensor,
skin_bone_indices: npt.ArrayLike | torch.Tensor,
skin_bone_weights: npt.ArrayLike | torch.Tensor,
skin_bone_node_indices: npt.ArrayLike | torch.Tensor,
inverse_bind_matrices: npt.ArrayLike | torch.Tensor,
skeleton_global_matrices: npt.ArrayLike | torch.Tensor,
) → dict[str, numpy.typing.NDArray[numpy.float32]][native]

CPU-skin bind-space positions and normals.

Shapes use V=vertices, B=skin bones, and S=skeleton nodes.

Parameters:
  • bind_positions – Float32 vertex positions with shape (V, 3).

  • bind_normals – Float32 vertex normals with shape (V, 3).

  • skin_bone_indices – Int32 skin-bone indices with shape (V, 4).

  • skin_bone_weights – Float32 skin-bone weights with shape (V, 4).

  • skin_bone_node_indices – Bone-to-node map with shape (B,).

  • inverse_bind_matrices – Float32 transforms with shape (B, 4, 4).

  • skeleton_global_matrices – Skeleton globals with shape (S, 4, 4).

Returns:

Float32 positions and normals arrays with shape (V, 3).

kangengine.animation.compute_skinning_matrices(
skin_bone_node_indices: npt.ArrayLike | torch.Tensor,
inverse_bind_matrices: npt.ArrayLike | torch.Tensor,
skeleton_global_matrices: npt.ArrayLike | torch.Tensor,
) → numpy.typing.NDArray[numpy.float32][native]

Return skinning matrices (B, 4, 4) from B skin bones and S nodes.

kangengine.animation.compute_skinning_matrices_into(
skin_bone_node_indices: npt.ArrayLike | torch.Tensor,
inverse_bind_matrices: npt.ArrayLike | torch.Tensor,
skeleton_global_matrices: npt.ArrayLike | torch.Tensor,
output: npt.ArrayLike | torch.Tensor,
) → numpy.typing.NDArray[numpy.float32][native]

Write and return skinning matrices using output shape (B, 4, 4).

class kangengine.animation.SkeletonTree[native]

Read-only skeleton hierarchy and local bind transforms.

index(name: str) → int

Return the node index for a name.

Raises:

RuntimeError – If the name is not in the skeleton tree.

local_rotation(index: int) → Quat

Return a node’s local bind rotation.

local_translation(index: int) → Vec3

Return a node’s local bind translation.

node_name(index: int) → str

Return a skeleton node name.

node_names() → list[str]

Return S skeleton node names.

num_joints() → int

Return S, the number of skeleton nodes.

parent_index(index: int) → int

Return the parent node index, or -1 for the root.

parent_indices() → list[int]

Return S parent indices.

print() → None

Print the hierarchy for debugging.

class kangengine.animation.SkeletonMotion[native]

Sampled skeleton animation with root motion and local rotations.

duration() → float

Return duration in seconds.

fps() → float

Return frames per second.

frame(frame_index: int) → SkeletonState

Return the pose at one frame.

static from_arrays(
skeleton_tree: SkeletonTree,
root_translations: npt.ArrayLike | torch.Tensor,
local_rotations_wxyz: npt.ArrayLike | torch.Tensor,
fps: float,
motion_name: str = 'Motion',
) → SkeletonMotion

Create a motion from root (F, 3) and WXYZ rotations (F, J, 4).

global_angular_accelerations() → _Float32Array

Compute global joint angular accelerations with shape (F, J, 3).

global_angular_velocities() → _Float32Array

Compute global joint angular velocities with shape (F, J, 3).

global_linear_accelerations() → _Float32Array

Compute global joint linear accelerations with shape (F, J, 3).

global_linear_velocities() → _Float32Array

Compute global joint linear velocities with shape (F, J, 3).

global_matrices() → _Float32Array

Compute global transforms with shape (F, J, 4, 4).

global_positions() → _Float32Array

Compute global joint positions with shape (F, J, 3).

global_rotations_wxyz() → _Float32Array

Compute WXYZ global joint rotations with shape (F, J, 4).

local_rotation(frame: int, joint: int) → Quat

Return one node’s local rotation at one frame.

local_rotations_wxyz() → _Float32Array

Return WXYZ local rotations with shape (F, J, 4).

local_rotations_wxyz_flat() → list[float]

Return flattened WXYZ rotations with logical shape (F, S, 4).

motion_name() → str

Return the clip name.

node_names() → list[str]

Return S skeleton node names.

num_frames() → int

Return F, the number of frames.

num_joints() → int

Return S, the number of skeleton nodes.

parent_indices() → list[int]

Return S parent indices.

root_linear_accelerations() → _Float32Array

Compute root linear accelerations with shape (F, 3).

root_linear_velocities() → _Float32Array

Compute root linear velocities with shape (F, 3).

root_translation(frame: int) → Vec3

Return the root translation at one frame.

root_translations() → _Float32Array

Return root translations with shape (F, 3).

root_translations_flat() → list[float]

Return flattened root translations with logical shape (F, 3).

sample(time: float, loop: bool = True) → SkeletonState

Sample a pose at time in seconds.

sample_into(
self: SkeletonMotion,
time: float,
state: KE::Animation::SkeletonState,
loop: bool = True,
) → None

Sample into a reusable compatible SkeletonState.

property skeleton_tree

Return the motion’s read-only skeleton hierarchy.

SkeletonMotion is the canonical public motion container. Importers such as BVHLoader and AMASSLoader return it directly; preprocessing code should construct edited clips with SkeletonMotion.from_arrays(). Batched FK, linear/angular velocity, and acceleration arrays are computed through its global_* and root_* methods.

class kangengine.animation.Transform[native]

Forward-kinematics transform result.

property rotation

Return the transform rotation.

property translation

Return the transform translation.

class kangengine.animation.SkeletonState[native]

Skeleton pose stored as root translation and S node rotations.

compute_global_matrices() → _Float32Array

Return global float32 matrices with shape (S, 4, 4).

compute_global_positions() → list[Vec3]

Return S global node positions.

compute_global_transforms() → list[Transform]

Return S global forward-kinematics transforms.

static from_rotation_and_root_translation(
tree: SkeletonTree,
rotations_wxyz: npt.ArrayLike | torch.Tensor,
root_translation: npt.ArrayLike | torch.Tensor,
is_local: bool = True,
) → SkeletonState

Create a pose from WXYZ rotations (S, 4) and root (3,).

get_joint_quat(index: int) → Quat

Return one stored node rotation.

is_local() → bool

Return whether rotations are local to parent nodes.

num_joints() → int

Return S, the number of skeleton nodes.

print_global_positions() → None

Print global node positions for debugging.

root_translation() → Vec3

Return the root translation.

set_joint_quat_wxyz(
index: int,
quat_wxyz: npt.ArrayLike | torch.Tensor,
) → None

Set a skeleton node’s quaternion without changing coordinate frames.

Parameters:
  • index – Skeleton node index, including the root.

  • quat_wxyz – WXYZ quaternion of shape (4,) in the state’s local or global convention, as indicated by is_local().

set_root_translation(translation: npt.ArrayLike | torch.Tensor) → None

Set the root translation from shape (3,).

property skeleton_tree

Return the state’s read-only skeleton hierarchy.

Batch motion matching

Prepare shared data once, then search and advance independent references. See the motion matching guide for a minimal example and runnable Newton viewers.

class kangengine.animation.MotionMatchingBatchSearch(
database: MotionMatchingDatabase,
*,
device: str | device = 'cpu',
dtype: dtype = torch.float32,
distance_mode: str = 'matrix',
query_chunk_size: int = 1024,
frame_chunk_size: int = 4096,
) → None[python]

Compare batched queries with every candidate frame on CPU or CUDA.

All environments share the search data; chunks limit working memory. Matrix distances are fast; direct distances reduce rounding errors for nearly identical features. Equal computed costs select the first row. Treat tensors as read-only; rebuild to change features or normalization.

Work scales with query count * candidate count * feature width. Matrix-mode near ties depend on Torch matmul precision and cancellation near zero. Use distance_mode=”direct”, dtype=torch.float64 for slower CPU comparisons.

normalize(raw_queries: Tensor) → Tensor

Normalize raw features […, D] using the database’s feature layout.

Return type:

Tensor

search(
queries: Tensor,
*,
current_motion_ids: Tensor | None = None,
current_times: Tensor | None = None,
continuation_bias: float = 0.0,
allowed_motion_mask: Tensor | None = None,
) → MotionMatchBatch

Search normalized queries [N, D] without host/device transfers.

Parameters:
  • queries (Tensor) – Finite features on the search device, with its dtype.

  • current_motion_ids (Tensor | None) – Valid clip IDs [N], paired with current_times.

  • current_times (Tensor | None) – Seconds within each current clip [N].

  • continuation_bias (float) – Nonnegative cost reduction for the candidate nearest current_times; favors continuing the current clip.

  • allowed_motion_mask (Tensor | None) – Boolean [M] or [N, M] mask on the search device. None allows every clip. M is the number of clips.

Return type:

MotionMatchBatch

class kangengine.animation.MotionMatchBatch(row_ids, motion_ids, frame_ids, times, costs)[python]

Bases: NamedTuple

One match per query; all tensors have shape [N].

No eligible clip gives IDs of -1, NaN times, and infinite costs. Controllers leave those environments unchanged.

costs

Alias for field number 4

frame_ids

Alias for field number 2

motion_ids

Alias for field number 1

row_ids

Alias for field number 0

times

Alias for field number 3

class kangengine.animation.MotionMatchingBatchController(
search: MotionMatchingBatchSearch,
molib: MotionLibrary[BackendSample],
*,
num_envs: int,
transition_half_life: float = 0.1,
) → None[python]

Bases: Generic[BackendSample]

Align and smooth native motion targets for independent environments.

Keep the shared search and library unchanged, with matching clips and order. Requires a floating-root PhysX, Newton, or MuJoCo adapter and body tracks. The task calls select() to choose targets, advance() to move time, and sample_robot_state() to read targets. Explicit DB reference tracks drive placement without filtering robot poses.

Keep inputs on the shared library/search device; runtime calls do not move tensors between CPU and GPU. Reference tracks are uploaded once at creation. Without a track, root forward directions must project onto the ground plane.

Joints and world body tracks are smoothed separately; bodies are not exact FK of the smoothed joints. The CPU player smooths local skeleton rotations. Joint targets are not clamped to limits. A zero transition_half_life disables smoothing; precompute_kinematics=True is required on the library.

advance(dt: float) → None

Advance all environments by nonnegative seconds; clamp at clip ends.

finished marks environments whose clips have ended; select new clips explicitly.

Return type:

None

property finished

Boolean [N] mask; select a new match before advancing past clip ends.

hold(env_ids: Tensor | None = None) → None

Freeze the current output pose and zero root, joint, and body rates.

held is a borrowed read-only [N] mask. Both playback and smoothing clocks stop, including future samples. select() preserves held rows; omit them from calls to select() to avoid their search work entirely. Environment selections are integer indices on the library device.

Return type:

None

reset(
env_ids: Tensor | None = None,
*,
motion_ids: Tensor | int = 0,
times: Tensor | float = 0.0,
root_pos: Tensor | None = None,
root_quat_wxyz: Tensor | None = None,
) → None

Reset selected environments without blending.

IDs/times are scalars or [N], where N is the selected environment count. World root_pos [N, 3] and root_quat_wxyz [N, 4] place the DB reference track, defaulting to zero and identity. Without a track they place the source root heading, retaining source height when root_pos is omitted. Supply tensors on the library device.

Return type:

None

resume(env_ids: Tensor | None = None) → None

Resume held rows by blending from their frozen pose and zero rates.

A zero transition half-life resumes source velocity immediately. transition() can instead resume directly into a chosen clip.

Return type:

None

sample_reference_state(
env_ids: Tensor | None = None,
) → tuple[Tensor, Tensor, Tensor, Tensor]

Read the world reference frame used to build matching queries.

Return type:

tuple[Tensor, Tensor, Tensor, Tensor]

Returns:

(pos_w, quat_wxyz_w, vel_w, ang_vel_w), with shapes [N, 3], [N, 4], [N, 3], [N, 3]. Units are meters, seconds, and radians. Explicit tracks ignore pose smoothing and use right segment derivatives, zero at clip ends. Without a track, returns the smoothed output root position, heading, and root velocities.

sample_robot_state(
env_ids: Tensor | None = None,
*,
future_offsets: Tensor | None = None,
) → tuple[BackendSample, BodyMotionState]

Read independent target snapshots without changing playback.

Returns [N, …] for selected environments. Nonnegative future_offsets [K] in seconds give [N, K, …], continuing current clips and smoothing. Future times clamp at clip ends; future matches are not predicted.

The first state uses the library adapter’s format: PhysXMotionState has split root fields and logical joint_pos/joint_vel; NewtonMotionState has joint_q (XYZW) and joint_qd; MuJoCoMotionState has qpos (WXYZ) and qvel. Newton root angular rates are world-space, ball rates parent-space; MuJoCo angular rates are local. Newton and MuJoCo support ball joints. The second state always uses world-space body poses and rates with WXYZ rotations. Fields such as body_pos_w have shape [N, bodies, 3].

Return type:

tuple[TypeVar(BackendSample), BodyMotionState]

select(
queries: Tensor,
*,
env_ids: Tensor | None = None,
continuation_bias: float = 0.01,
allowed_motion_mask: Tensor | None = None,
) → MotionMatchBatch

Search [selected N, D] queries and transition changed matches.

A nearest-frame continuation retains subframe time and existing smoothing. Rows with no eligible match retain their current playback state. Build queries with the database’s feature layout, coordinates, and dtype, then call search.normalize(). NumPy scalar query helpers are not GPU builders. allowed_motion_mask follows MotionMatchingBatchSearch.search().

Return type:

MotionMatchBatch

transition(
env_ids: Tensor | None = None,
*,
motion_ids: Tensor | int,
times: Tensor | float,
root_pos: Tensor | None = None,
root_quat_wxyz: Tensor | None = None,
) → None

Switch clips with continuous pose and velocity when smoothing is enabled.

Align reference tracks across the switch, or root headings and planar positions without a track. Override placement as in reset(). Held environments resume from their frozen pose and zero rates. A zero half-life switches immediately without smoothing.

Return type:

None