Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

HG16: in progress: a SOMA body posed from a motion's turns in the SDK. raea-sys-body turns.rs: from_turns (a joint's world turn from bind is the motion's turn after the turn from bind to SOMA's T-pose; a joint the motion doesn't name rides its parent) and set_twists (each limb segment's four twist joints by SOMA's shares); native call character.turns; raea/character turnsPose and TurnsClip. Test: a forearm's twist joints take 5 to 95 per cent of the hand's turn, an upper arm's stay with the chest near the shoulder

shinyobjectzbdb77110de2e
diff --git a/docs/hands.feature b/docs/hands.feature
index 0e3083d8..45bf057c 100644
--- a/docs/hands.feature
+++ b/docs/hands.feature
@@ -512,7 +512,9 @@ Feature: Procedural arms and hands: a character reaches for, takes, holds, carri
# twist joints take SOMA's shares, and each joint's turn is taken relative to its parent. `<Character
# body="soma">` drew the run and leap with no change to the SDK. The body's build and the clip's
# conversion are scripts in the test project for now (tools/soma_body.py for Blender,
- # tools/kimodo_clip.py), and the pose is worked out in the composition: HG16 moves them into the SDK.
+ # tools/kimodo_clip.py): HG16 moves them into the SDK. The pose itself is in the SDK: raea-sys-body
+ # turns.rs `from_turns` and `set_twists`, the native call character.turns, raea/character's `turnsPose`;
+ # the same frame drawn through it matches the composition's own arithmetic (SSIM 0.999996).
Then SOMA's body is posed by `<Character>`, its twist joints included
Scenario: HG16. A SOMA body is a raea body
diff --git a/runtime/calls/src/lib.rs b/runtime/calls/src/lib.rs
index 90b8add2..236e1846 100644
--- a/runtime/calls/src/lib.rs
+++ b/runtime/calls/src/lib.rs
@@ -178,6 +178,7 @@ pub fn call(name: &str, v: &Value) -> R<Value> {
"character.fit" => raea_sys_grab::fit_json(v),
"character.hand" => raea_sys_grab::hand_json(v),
"character.soma" => raea_sys_grab::soma_json(v),
+ "character.turns" => raea_sys_grab::turns_json(v),
"fonts.families" => Ok(families().into()),
"fonts.google" => {
let family = s(v, "family")?;
@@ -230,6 +231,7 @@ pub fn register() {
("character.fit", raea_sys_grab::FIT_ARGS, raea_sys_grab::FIT_ANSWER, "a pose fitted to points of the body seen somewhere (joints or marks on them, from a capture, a tracker or another rig), and their root-mean-square miss, metres"),
("character.hand", raea_sys_grab::HAND_ARGS, raea_sys_grab::HAND_ANSWER, "a hand shaped by a few numbers of a model of real hand poses (none: the average relaxed hand; the first opens it, positive, and closes it), on a pose; and that hand read back: its numbers and how odd it is (0: the average hand)"),
("character.soma", raea_sys_grab::SOMA_ARGS, raea_sys_grab::SOMA_ANSWER, "the pose that has a body's bones pointing as a SOMA body's do (SOMA: the 78-joint skeleton of NVIDIA's motion models and datasets), from SOMA's joint names and where each joint is"),
+ ("character.turns", raea_sys_grab::TURNS_ARGS, raea_sys_grab::TURNS_ANSWER, "a SOMA body's pose from a motion given as turns (each named joint's world turn from SOMA's T-pose, as Kimodo writes them, and where the hips are), with the body's twist joints set"),
("fonts.families", "{}", "string[]", "the system's font families by name, sorted, as fontique (bevy_text's FontCx) lists them"),
("fonts.google", "{ family: string }", "{ family: string }", "a Google Fonts family the page loads (its Latin faces, every weight and style, fetched once through raea's URL cache), as a stylesheet link loads it in Chrome (raea/text loadFont)"),
("fonts.atlases", "{ font: string; size: number; text: string }", "{ width: number; height: number; src: string }[]", "bevy_text's glyph atlases for a text in a font file at a size px, each page a PNG data: URL, as Bevy's FontAtlasSet holds them"),
diff --git a/sdk/character/src/character.tsx b/sdk/character/src/character.tsx
index 01c8bef9..406e7c3d 100644
--- a/sdk/character/src/character.tsx
+++ b/sdk/character/src/character.tsx
@@ -21,5 +21,5 @@ export type { Quat, Joint, Skeleton, Pose, Posed, Side, Finger, HandShape, Closi
export { take, fetch, fitPose, handShape, placedPose, walkUp } from "./take";
export type { TakeThing, TakeSpec, Taken, Mark } from "./take";
// motion on SOMA's skeleton (NVIDIA's motion models and datasets) played on a raea body
-export { readSomaUsda, somaPose } from "./soma";
-export type { SomaClip } from "./soma";
+export { readSomaUsda, somaPose, turnsPose } from "./soma";
+export type { SomaClip, TurnsClip } from "./soma";
diff --git a/sdk/character/src/soma.ts b/sdk/character/src/soma.ts
index 45a517ec..220845c4 100644
--- a/sdk/character/src/soma.ts
+++ b/sdk/character/src/soma.ts
@@ -63,3 +63,21 @@ export function somaPose(skel: Skeleton, clip: SomaClip, frame: number): Pose {
const joints = skel.joints.map((j) => ({ name: j.name, parent: j.parent, head: j.head, tail: j.tail }));
return native("character.soma", { joints, names: clip.names, at, eyes: skel.landmarks?.eyes }).pose;
}
+
+/** A motion on SOMA's skeleton given as turns, as Kimodo writes one: per frame where the hips are (metres) and each
+ * named joint's world turn from SOMA's T-pose. */
+export interface TurnsClip {
+ fps: number;
+ names: string[];
+ root: Vec3[];
+ turns: Quat[][];
+}
+
+/** A SOMA body (a skeleton whose rig is "soma", with each joint's turn from bind to the T-pose in `tpose`) posed by
+ * a motion's turns at a frame, its twist joints set (the native call character.turns): nothing is fitted, since the
+ * body and the motion share a skeleton. */
+export function turnsPose(skel: Skeleton & { tpose?: Record<string, Quat> }, clip: TurnsClip, frame: number): Pose {
+ const f = Math.max(0, Math.min(clip.turns.length - 1, Math.round(frame)));
+ const joints = skel.joints.map((j) => ({ name: j.name, parent: j.parent, head: j.head, tail: j.tail }));
+ return native("character.turns", { joints, tpose: skel.tpose ?? {}, names: clip.names, turns: clip.turns[f], root: clip.root[f] }).pose;
+}
diff --git a/sdk/raea/src/native-calls.ts b/sdk/raea/src/native-calls.ts
index ade2abed..60ebd973 100644
--- a/sdk/raea/src/native-calls.ts
+++ b/sdk/raea/src/native-calls.ts
@@ -44,6 +44,8 @@ export interface NativeCalls {
"character.soma": { args: { joints: { name: string; parent: number; head: [number, number, number]; tail: [number, number, number] }[]; names: string[]; at: [number, number, number][]; eyes?: [number, number, number] }; answer: { pose: { root: [number, number, number]; turns: [number, number, number, number][] } } };
/** a frame of a character taking a thing with its hands (reach, grab, lift, carry, put down or throw): the pose to draw and where the thing is, with how far a wrist missed (metres) and how far the body was turned from its own motion (degrees) */
"character.take": { args: { joints: { name: string; parent: number; head: [number, number, number]; tail: [number, number, number] }[]; t: number; base: { t: number; root: [number, number, number]; turns: [number, number, number, number][] }[]; thing: { ball?: number; box?: [number, number, number]; capsule?: [number, number]; cylinder?: [number, number]; at: [number, number, number]; turn?: [number, number, number, number] }; start: number; grab?: number; carried?: number; carry?: [number, number, number]; hand?: "L" | "R"; lower?: number; holds?: { side: "L" | "R"; at: [number, number, number]; normal: [number, number, number]; along?: [number, number, number]; shape?: number[] }[]; path?: { t: number; carry: [number, number, number]; tilt?: [number, number, number, number] }[]; weight?: number; pass?: number; slide?: { t: number; at: [number, number, number]; turn?: [number, number, number, number] }[]; leave?: number; avoid?: { ball?: number; box?: [number, number, number]; capsule?: [number, number]; cylinder?: [number, number]; at: [number, number, number]; turn?: [number, number, number, number] }[]; put?: { at: number; down: number; place: [number, number, number] }; throw?: { at: number; velocity: [number, number, number]; floor?: number } }; answer: { pose: { root: [number, number, number]; turns: [number, number, number, number][] }; thing: { at: [number, number, number]; turn: [number, number, number, number] }; phase: "Before" | "Reach" | "Lift" | "Carry" | "Release" | "After"; hands: 1 | 2; miss: number; moved: number; limited: boolean; stand: { at: [number, number, number]; yaw: number }; reach: { ok: boolean; move: number } } };
+ /** a SOMA body's pose from a motion given as turns (each named joint's world turn from SOMA's T-pose, as Kimodo writes them, and where the hips are), with the body's twist joints set */
+ "character.turns": { args: { joints: { name: string; parent: number; head: [number, number, number]; tail: [number, number, number] }[]; tpose?: Record<string, [number, number, number, number]>; names: string[]; turns: [number, number, number, number][]; root: [number, number, number] }; answer: { pose: { root: [number, number, number]; turns: [number, number, number, number][] } } };
/** raea's command line (render, play, guide, bundle, types; the media verbs: raea media, raea ffmpeg), run in process in cwd */
"cli.raea": { args: { args: string[]; cwd: string }; answer: { exit: number; stdout: string; stderr: string } };
/** a headless run ends with this exit code */
diff --git a/systems/body/src/json.rs b/systems/body/src/json.rs
index 9713f037..4cbf7d54 100644
--- a/systems/body/src/json.rs
+++ b/systems/body/src/json.rs
@@ -8,6 +8,7 @@ use crate::fit::{Mark, fit};
use crate::prior::{coefficients, oddness, shape};
use crate::rig::{Pose, Side, Skeleton};
use crate::soma::from_soma;
+use crate::turns::from_turns;
pub fn num(v: &Value, what: &str) -> Result<f32, String> {
v.as_f64().map(|n| n as f32).ok_or_else(|| format!("character.take: {what} isn't a number"))
@@ -95,6 +96,27 @@ pub fn soma_json(v: &Value) -> Result<Value, String> {
Ok(json!({ "pose": posed(&pose) }))
}
+pub const TURNS_ARGS: &str = "{ joints: { name: string; parent: number; head: [number, number, number]; tail: [number, number, number] }[]; tpose?: Record<string, [number, number, number, number]>; names: string[]; turns: [number, number, number, number][]; root: [number, number, number] }";
+pub const TURNS_ANSWER: &str = "{ pose: { root: [number, number, number]; turns: [number, number, number, number][] } }";
+
+/// `character.turns`: a SOMA body's pose from a motion's turns, its twist joints set (turns.rs).
+pub fn turns_json(v: &Value) -> Result<Value, String> {
+ let skel = Skeleton::from_value(v)?;
+ let mut tpose = std::collections::HashMap::new();
+ for (name, turn) in v["tpose"].as_object().into_iter().flatten() {
+ tpose.insert(name.clone(), quat(turn, "a joint's turn to the T-pose")?);
+ }
+ let names: Vec<String> = v["names"].as_array().ok_or("character.turns: no names")?.iter().filter_map(|n| n.as_str().map(String::from)).collect();
+ let mut turns = Vec::with_capacity(names.len());
+ for turn in v["turns"].as_array().ok_or("character.turns: no turns")? {
+ turns.push(quat(turn, "a joint's turn")?);
+ }
+ if turns.len() != names.len() {
+ return Err(format!("character.turns: {} names for {} turns", names.len(), turns.len()));
+ }
+ Ok(json!({ "pose": posed(&from_turns(&skel, &tpose, &names, &turns, vec3(&v["root"], "root")?)) }))
+}
+
/// a pose as the calls answer it: the root's place and every joint's turn
pub fn posed(pose: &Pose) -> Value {
let turns: Vec<[f32; 4]> = pose.turns.iter().map(|q| q.to_array()).collect();
diff --git a/systems/body/src/lib.rs b/systems/body/src/lib.rs
index 7e48f048..7dd48473 100644
--- a/systems/body/src/lib.rs
+++ b/systems/body/src/lib.rs
@@ -19,11 +19,13 @@ pub mod prior;
pub mod rig;
pub mod shape;
pub mod soma;
+pub mod turns;
pub use arm::{ArmOptions, IkReport, forearm_twist, reach, settle_hinge, twist_joints, two_bone};
pub use soma::{from_soma, raea_joint};
+pub use turns::{from_turns, set_twists};
pub use fit::{Mark, fit, marks_of};
-pub use json::{FIT_ANSWER, FIT_ARGS, HAND_ANSWER, HAND_ARGS, SOMA_ANSWER, SOMA_ARGS, fit_json, hand_json, soma_json};
+pub use json::{FIT_ANSWER, FIT_ARGS, HAND_ANSWER, HAND_ARGS, SOMA_ANSWER, SOMA_ARGS, TURNS_ANSWER, TURNS_ARGS, fit_json, hand_json, soma_json, turns_json};
pub use limits::{Angles, angles_of, clamp_turn, violations};
pub use shape::{Hit, Solid, Thing};
pub use rig::{HandRest, Pose, Posed, Sample, Side, Skeleton, hand_rest, mannequin};
diff --git a/systems/body/src/turns.rs b/systems/body/src/turns.rs
new file mode 100644
index 00000000..402bc59f
--- /dev/null
+++ b/systems/body/src/turns.rs
@@ -0,0 +1,62 @@
+//! A motion given as turns, posed on a SOMA body. Kimodo (and anything else that speaks SOMA's skeleton in turns)
+//! says how each joint is turned in the world from SOMA's T-pose. A raea body made from SOMA's rig (rig "soma")
+//! has those joints under SOMA's names, bound in SOMA's bind pose, so nothing is fitted: a joint's world turn from
+//! bind is the motion's turn after the turn from bind to the T-pose, a joint the motion doesn't name rides its
+//! parent, and each limb segment's four twist joints take SOMA's shares of the turn about the segment (arm.rs).
+
+use std::collections::HashMap;
+
+use glam::{Quat, Vec3};
+
+use crate::arm::{twist_about, twist_joints};
+use crate::rig::{Pose, Skeleton};
+
+/// SOMA's limb segments that carry twist joints: the joint each hangs from, the joint at its far end, and whether
+/// it is an upper segment (it undoes its own joint's twist) or a lower one (it takes up its far joint's)
+const SEGMENTS: [(&str, &str, bool); 4] = [("Arm", "ForeArm", true), ("ForeArm", "Hand", false), ("Leg", "Shin", true), ("Shin", "Foot", false)];
+
+/// the signed angle of a turn about a unit axis: its twist, radians
+fn angle_about(q: Quat, axis: Vec3) -> f32 {
+ let t = twist_about(q, axis);
+ 2.0 * Vec3::new(t.x, t.y, t.z).dot(axis).atan2(t.w)
+}
+
+/// Sets a SOMA body's twist joints (`{segment}Twist1` to 4) in `world`, every joint's world turn from bind, from
+/// the turns of the joints at each segment's two ends. A body without twist joints is left as it is.
+pub fn set_twists(skel: &Skeleton, world: &mut [Quat]) {
+ for side in ["Left", "Right"] {
+ for (seg, far, upper) in SEGMENTS {
+ let (Some(s), Some(n)) = (skel.joint(&format!("{side}{seg}")), skel.joint(&format!("{side}{far}"))) else { continue };
+ let axis = (world[s] * (skel.joints[n].head - skel.joints[s].head)).normalize_or_zero();
+ if axis == Vec3::ZERO {
+ continue;
+ }
+ let before = skel.joints[s].parent.map_or(Quat::IDENTITY, |p| world[p]);
+ let (start, end) = if upper { (angle_about(world[s] * before.inverse(), axis), 0.0) } else { (0.0, angle_about(world[n] * world[s].inverse(), axis)) };
+ for (k, turn) in twist_joints(axis, start, end, upper).into_iter().enumerate() {
+ if let Some(t) = skel.joint(&format!("{side}{seg}Twist{}", k + 1)) {
+ world[t] = (turn * world[s]).normalize();
+ }
+ }
+ }
+ }
+}
+
+/// The pose of a SOMA body from a motion's turns: `names` and `turns` are the motion's joints and each one's world
+/// turn from the T-pose; `tpose` is each of the body's joints' turn from bind to the T-pose, by name (a joint
+/// without one is taken as bound in the T-pose); `root` is where the hips are. Ends, eyes and the jaw are not
+/// turned by a motion's body joints and ride their parents.
+pub fn from_turns(skel: &Skeleton, tpose: &HashMap<String, Quat>, names: &[String], turns: &[Quat], root: Vec3) -> Pose {
+ let given: HashMap<&str, Quat> = names.iter().map(String::as_str).zip(turns.iter().copied()).collect();
+ let mut world = vec![Quat::IDENTITY; skel.joints.len()];
+ for (i, joint) in skel.joints.iter().enumerate() {
+ let rides = joint.name.ends_with("End") || joint.name.ends_with("Eye") || joint.name == "Jaw";
+ world[i] = match given.get(joint.name.as_str()).filter(|_| !rides) {
+ Some(turn) => (*turn * tpose.get(&joint.name).copied().unwrap_or(Quat::IDENTITY)).normalize(),
+ None => joint.parent.map_or(Quat::IDENTITY, |p| world[p]),
+ };
+ }
+ set_twists(skel, &mut world);
+ let turns = skel.joints.iter().enumerate().map(|(i, j)| j.parent.map_or(world[i], |p| (world[p].inverse() * world[i]).normalize())).collect();
+ Pose { root, turns }
+}
diff --git a/systems/body/tests/body.rs b/systems/body/tests/body.rs
index 7dd97113..15628a0d 100644
--- a/systems/body/tests/body.rs
+++ b/systems/body/tests/body.rs
@@ -141,3 +141,41 @@ fn a_soma_body_of_other_proportions_is_followed_bone_for_bone() {
assert!(side.abs() < 25.0, "{name} bends {side} degrees sideways");
}
}
+
+#[test]
+fn a_soma_body_takes_a_motions_turns_and_spreads_twist_along_its_limbs() {
+ use raea_sys_body::rig::Joint;
+ // one arm of a SOMA body: a chest, an upper arm and forearm along +x, each with four twist joints, and a hand
+ let j = |name: &str, parent: Option<usize>, x: f32| Joint { name: name.into(), parent, head: Vec3::new(x, 1.4, 0.0), tail: Vec3::new(x + 0.05, 1.4, 0.0) };
+ let mut joints = vec![j("Chest", None, 0.0), j("LeftArm", Some(0), 0.2), j("LeftForeArm", Some(1), 0.5), j("LeftHand", Some(2), 0.75)];
+ for k in 0..4 {
+ joints.push(j(&format!("LeftArmTwist{}", k + 1), Some(1), 0.2 + 0.06 * k as f32));
+ joints.push(j(&format!("LeftForeArmTwist{}", k + 1), Some(2), 0.5 + 0.05 * k as f32));
+ }
+ let s = Skeleton::new(joints);
+ let names: Vec<String> = ["Chest", "LeftArm", "LeftForeArm", "LeftHand"].map(String::from).to_vec();
+ let about_x = |q: Quat| 2.0 * q.x.atan2(q.w);
+ // the hand turned 1.2 about the forearm: the forearm's twist joints take 5 per cent to 95 per cent of it
+ let turn = Quat::from_axis_angle(Vec3::X, 1.2);
+ let p = from_turns(&s, &Default::default(), &names, &[Quat::IDENTITY, Quat::IDENTITY, Quat::IDENTITY, turn], Vec3::new(0.0, 1.4, 0.0));
+ let w = s.fk(&p);
+ for (k, share) in [0.05, 1.0 / 3.0, 2.0 / 3.0, 0.95].into_iter().enumerate() {
+ let t = s.joint(&format!("LeftForeArmTwist{}", k + 1)).unwrap();
+ assert!((about_x(w.rot[t]) - 1.2 * share).abs() < 1e-3, "forearm twist {k}: {}", about_x(w.rot[t]));
+ assert!(about_x(w.rot[s.joint(&format!("LeftArmTwist{}", k + 1)).unwrap()]).abs() < 1e-3);
+ }
+ assert!((about_x(w.rot[3]) - 1.2).abs() < 1e-3 && w.pos[3].distance(Vec3::new(0.75, 1.4, 0.0)) < 1e-5);
+ // the whole arm turned 0.8 about itself at the shoulder: the skin near the shoulder stays with the chest
+ let p = from_turns(&s, &Default::default(), &names, &[Quat::IDENTITY, Quat::from_axis_angle(Vec3::X, 0.8), Quat::from_axis_angle(Vec3::X, 0.8), Quat::from_axis_angle(Vec3::X, 0.8)], Vec3::ZERO);
+ let w = s.fk(&p);
+ for (k, share) in [0.05, 1.0 / 3.0, 2.0 / 3.0, 0.95].into_iter().enumerate() {
+ let t = s.joint(&format!("LeftArmTwist{}", k + 1)).unwrap();
+ assert!((about_x(w.rot[t]) - 0.8 * share).abs() < 1e-3, "upper twist {k}: {}", about_x(w.rot[t]));
+ }
+ // a joint's turn to the T-pose comes before the motion's turn, and a joint the motion doesn't name rides its parent
+ let tpose = std::collections::HashMap::from([("LeftArm".to_string(), Quat::from_axis_angle(Vec3::Z, 0.5))]);
+ let p = from_turns(&s, &tpose, &names[..2].to_vec(), &[Quat::IDENTITY, Quat::from_axis_angle(Vec3::Y, 0.3)], Vec3::new(0.0, 0.1, 0.0));
+ let w = s.fk(&p);
+ let want = Quat::from_axis_angle(Vec3::Y, 0.3) * Quat::from_axis_angle(Vec3::Z, 0.5);
+ assert!(w.rot[1].dot(want).abs() > 0.99999 && w.rot[2].dot(want).abs() > 0.99999 && p.root == Vec3::new(0.0, 0.1, 0.0));
+}
diff --git a/systems/grab/src/lib.rs b/systems/grab/src/lib.rs
index daba9725..c9bbb6c6 100644
--- a/systems/grab/src/lib.rs
+++ b/systems/grab/src/lib.rs
@@ -22,6 +22,6 @@ pub mod trunk;
pub use hand::{Grip, Hold, HoldOptions, Touch, curl, find_holds, wrist_for};
pub use interact::pick;
pub use json::{TAKE_ANSWER, TAKE_ARGS, take_json};
-pub use raea_sys_body::json::{FIT_ANSWER, FIT_ARGS, HAND_ANSWER, HAND_ARGS, SOMA_ANSWER, SOMA_ARGS, fit_json, hand_json, soma_json};
+pub use raea_sys_body::json::{FIT_ANSWER, FIT_ARGS, HAND_ANSWER, HAND_ARGS, SOMA_ANSWER, SOMA_ARGS, TURNS_ANSWER, TURNS_ARGS, fit_json, hand_json, soma_json, turns_json};
pub use take::{Frame, Key, Phase, Release, Take, perform};
pub use trunk::{clear, give_for, hand_points, look, own_solids, room, spread_for, stand_for, stoop, torso};