Skip to content

The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.

Models posed node by node: AnimationPose.nodes, each such model a pose of its own (#175)

Evan (Yifeng) Wang76672c7cac12
diff --git a/packages/scene/src/core.ts b/packages/scene/src/core.ts
index e53e4f8..7122a14 100644
--- a/packages/scene/src/core.ts
+++ b/packages/scene/src/core.ts
@@ -1241,11 +1241,21 @@ export class Mesh extends Object3D {
}
}
-/** A pose of an animated glTF asset: clip (by name) sampled at `time` seconds; looping by default. */
+/**
+ * A pose of an animated glTF asset: a clip (by name) sampled at `time` seconds (looping by default), then the nodes the
+ * game poses itself. Either may be left out: a skeleton posed by the game alone has only `nodes`.
+ */
export interface AnimationPose {
- clip: string;
- time: number;
+ clip?: string;
+ time?: number;
loop?: boolean;
+ /**
+ * Local transforms of nodes (joints) by name, over the clip's: 4 numbers, a rotation (quaternion x, y, z, w), or 7,
+ * a translation (x, y, z, in the node's parent's space) and then the rotation. A skinned mesh follows its joints
+ * (aim, look, procedural steps). Each model posed this way is skinned on its own; set a new object (or change these
+ * numbers and set it again) for a new pose.
+ */
+ nodes?: Record<string, ArrayLike<number>>;
}
/**
@@ -1818,8 +1828,9 @@ export class InstancedMesh extends Object3D {
/**
* Instance of an external glTF/GLB asset (path under the asset root). Skinned / animated assets (characters) are posed
- * by `animation`: set it once for a still, or every frame from a frame script (`{ clip: "Walk_Loop", time: f.time }`);
- * the engine samples the clip and skins the meshes. null = the file's rest pose.
+ * by `animation`: set it once for a still, or every frame from a frame script (`{ clip: "Walk_Loop", time: f.time }`,
+ * or joint by joint: `{ nodes: { spine: [x, y, z, w], ... } }`); the engine samples the clip, poses the named nodes and
+ * skins the meshes. null = the file's rest pose.
*/
export class GLTFModel extends Object3D {
override type = "GLTFModel";
diff --git a/packages/scene/src/engine.ts b/packages/scene/src/engine.ts
index 0caa2ce..3edcf94 100644
--- a/packages/scene/src/engine.ts
+++ b/packages/scene/src/engine.ts
@@ -174,11 +174,12 @@ type ObjectKindDesc =
/** `InstancedMesh`: `count` instances (its capacity) of triangle geometry (`materials[0]`) or procedural geometry. */
| { name: string; parent: number | null; castShadow: boolean; movable?: boolean; kind: "instanced"; geometry: number; procedural?: boolean; materials: number[]; count: number };
-/** Pose of an animated model: clip name, time (s), looping. */
+/** Pose of an animated model: clip name ("" for none), time (s), looping, nodes posed by name (4 or 7 numbers). */
export interface AnimationDesc {
clip: string;
time: number;
loop: boolean;
+ nodes?: Record<string, number[]>;
}
export interface SettingsDesc {
@@ -591,7 +592,7 @@ export class SceneBinding {
}
if (o instanceof GLTFModel) {
const a = animationDesc(o);
- if (a?.clip !== b.anim?.clip || a?.time !== b.anim?.time || a?.loop !== b.anim?.loop) {
+ if (!samePose(a, b.anim)) {
b.anim = a;
this.engine.animation(b.id, a);
stats.updated++;
@@ -1560,8 +1561,37 @@ function lightValues(l: Light, out: Float64Array): Float64Array {
function animationDesc(m: GLTFModel): AnimationDesc | null {
const a = m.animation;
if (!a) return null;
- if (typeof a.clip !== "string" || !Number.isFinite(a.time)) throw new TypeError(`${m.name || m.uri}: animation needs a clip name and a finite time`);
- return { clip: a.clip, time: a.time, loop: a.loop ?? true };
+ const who = m.name || m.uri;
+ if (a.clip !== undefined && typeof a.clip !== "string") throw new TypeError(`${who}: animation's clip is a name`);
+ if (a.time !== undefined && !Number.isFinite(a.time)) throw new TypeError(`${who}: animation's time must be finite`);
+ if (!a.clip && !a.nodes) throw new TypeError(`${who}: animation needs a clip or nodes`);
+ const d: AnimationDesc = { clip: a.clip ?? "", time: a.time ?? 0, loop: a.loop ?? true };
+ if (a.nodes) {
+ // (A copy: the game may change its arrays in place for the next frame.)
+ const nodes: Record<string, number[]> = {};
+ for (const [name, v] of Object.entries(a.nodes)) {
+ const n = Array.from(v);
+ if ((n.length !== 4 && n.length !== 7) || !n.every(Number.isFinite)) throw new TypeError(`${who}: animation node "${name}" needs 4 finite numbers (a rotation) or 7 (a translation, a rotation)`);
+ nodes[name] = n;
+ }
+ d.nodes = nodes;
+ }
+ return d;
+}
+
+function samePose(a: AnimationDesc | null, b: AnimationDesc | null): boolean {
+ if (!a || !b) return a === b;
+ if (a.clip !== b.clip || a.time !== b.time || a.loop !== b.loop) return false;
+ const an = a.nodes, bn = b.nodes;
+ if (!an || !bn) return an === bn;
+ const keys = Object.keys(an);
+ if (keys.length !== Object.keys(bn).length) return false;
+ for (const k of keys) {
+ const x = an[k]!, y = bn[k];
+ if (!y || x.length !== y.length) return false;
+ for (let i = 0; i < x.length; i++) if (x[i] !== y[i]) return false;
+ }
+ return true;
}
export function cameraDesc(c: PerspectiveCamera): CameraDesc {
diff --git a/packages/scene/test/engine.test.ts b/packages/scene/test/engine.test.ts
index 3e5c1c9..8f01e31 100644
--- a/packages/scene/test/engine.test.ts
+++ b/packages/scene/test/engine.test.ts
@@ -444,3 +444,30 @@ test("density grids: the grid goes before its volume, with its program's WGSL on
smoke.puff([1, 2, 3], 0.5, { density: 0.7, push: 2 });
assert.deepEqual([...smoke.grid!.pendingSources[0]].map((v) => +v.toFixed(3)), [1, 2, 3, 0.5, 0.7, 1, 0, 0, 0, 0, 0, 2]);
});
+
+test("a model posed node by node: the nodes reach the engine as a copy, again only when a number changes", async () => {
+ const { GLTFModel, PerspectiveCamera, RecordingEngine, Scene, SceneBinding } = await import("../src/index.ts");
+ const scene = new Scene();
+ const cam = new PerspectiveCamera();
+ scene.add(cam);
+ const spine = new Float32Array([0, 0, 0, 1]);
+ const body = new GLTFModel("assets/body.glb", { animation: { nodes: { spine, hip: [0, 1, 0, 0, 0, 0, 1] } } });
+ scene.add(body);
+ const engine = new RecordingEngine();
+ const b = new SceneBinding(engine, scene, cam);
+ b.sync();
+ const object = engine.take().find((c) => c[0] === "object" && (c[2] as { kind?: string }).kind === "model") as unknown as [string, number, { animation: unknown }];
+ assert.deepEqual(object[2].animation, { clip: "", time: 0, loop: true, nodes: { spine: [0, 0, 0, 1], hip: [0, 1, 0, 0, 0, 0, 1] } });
+ const poses = () => engine.take().filter((c) => c[0] === "animation").map((c) => c[2]);
+ body.animation = { nodes: { spine, hip: [0, 1, 0, 0, 0, 0, 1] } };
+ b.sync();
+ assert.deepEqual(poses(), [], "the same numbers: not sent again");
+ spine[2] = 0.5;
+ body.animation = { nodes: { spine, hip: [0, 1, 0, 0, 0, 0, 1] } };
+ b.sync();
+ assert.deepEqual(poses(), [{ clip: "", time: 0, loop: true, nodes: { spine: [0, 0, 0.5, 1], hip: [0, 1, 0, 0, 0, 0, 1] } }]);
+ body.animation = { nodes: { spine: [0, 0, 1] } };
+ assert.throws(() => b.sync(), /4 finite numbers/);
+ body.animation = {};
+ assert.throws(() => b.sync(), /a clip or nodes/);
+});
diff --git a/renderer/src/desc.rs b/renderer/src/desc.rs
index 64877dd..bf22f67 100644
--- a/renderer/src/desc.rs
+++ b/renderer/src/desc.rs
@@ -103,13 +103,20 @@ pub struct Dof {
pub sensor_width: f32,
}
-/// Pose of an animated model: clip (by name) sampled at `time` s.
+/// Pose of an animated model: clip (by name) sampled at `time` s, then the nodes the game poses itself (`nodes`).
+/// Without a clip the nodes not named stay as the file has them.
#[derive(Deserialize, Debug, Clone, PartialEq)]
pub struct Animation {
+ #[serde(default)]
pub clip: String,
+ #[serde(default)]
pub time: f32,
#[serde(default = "yes")]
pub r#loop: bool,
+ /// Local transforms of nodes by name, over the clip's: 4 numbers (rotation, quaternion xyzw) or 7 (translation xyz,
+ /// then the rotation). A skeleton posed by the game: aim, look, procedural steps, ragdolls.
+ #[serde(default)]
+ pub nodes: std::collections::BTreeMap<String, Vec<f32>>,
}
#[derive(Deserialize, Debug, Clone)]
diff --git a/renderer/src/live/inplace_tests.rs b/renderer/src/live/inplace_tests.rs
index 4af16cf..3746923 100644
--- a/renderer/src/live/inplace_tests.rs
+++ b/renderer/src/live/inplace_tests.rs
@@ -795,7 +795,7 @@ fn the_light_list_holds_its_triangles() {
// moves its node (a rigid model: the node is an instance), each against a build's picture.
let open_at_root = |w: &World| gpu::Gpu::new().and_then(|g| LiveCore::new(g, w, Path::new(".."), &presets, 96, 54));
let model = |animation| Kind::Model { uri: "tests/render/data/panel.glb".into(), nodes: None, animation, functions: vec![] };
- let slide = |time| Some(crate::desc::Animation { clip: "slide".into(), time, r#loop: true });
+ let slide = |time| Some(crate::desc::Animation { clip: "slide".into(), time, r#loop: true, nodes: Default::default() });
let small = Vec3::splat(0.05);
let mut w = world();
w.set_object(30, "still".into(), None, model(None), true, false).unwrap();
@@ -2011,7 +2011,7 @@ fn a_material_turned_glass_stops_casting_its_shadow_in_place() {
fn a_posed_rigid_model_is_posed_and_moved_in_place_with_the_nodes_its_clip_leaves_alone() {
let presets = crate::default_presets_dir();
let open = |w: &World| gpu::Gpu::new().and_then(|g| LiveCore::new(g, w, Path::new(".."), &presets, 96, 54));
- let slide = |time| Some(crate::desc::Animation { clip: "slide".into(), time, r#loop: true });
+ let slide = |time| Some(crate::desc::Animation { clip: "slide".into(), time, r#loop: true, nodes: Default::default() });
let model = |time| Kind::Model { uri: "tests/render/data/panel-slider.glb".into(), nodes: None, animation: slide(time), functions: vec![] };
let size = Vec3::splat(0.08);
let mut w = world();
@@ -2081,7 +2081,7 @@ fn a_posed_rigid_model_is_posed_and_moved_in_place_with_the_nodes_its_clip_leave
fn a_posed_rigid_model_under_groups_is_not_moved_by_a_new_pose() {
let presets = crate::default_presets_dir();
let open = |w: &World| gpu::Gpu::new().and_then(|g| LiveCore::new(g, w, Path::new(".."), &presets, 96, 54));
- let slide = |time| Some(crate::desc::Animation { clip: "slide".into(), time, r#loop: true });
+ let slide = |time| Some(crate::desc::Animation { clip: "slide".into(), time, r#loop: true, nodes: Default::default() });
let mut w = world();
w.set_object(50, "a".into(), None, Kind::Group, true, false).unwrap();
w.set_transform(50, Vec3::new(0.13, -0.27, 0.31), glam::Quat::from_euler(glam::EulerRot::XYZ, 0.37, -0.53, 0.71), Vec3::new(1.1, 0.9, 1.3)).unwrap();
@@ -2117,7 +2117,7 @@ fn a_posed_rigid_model_under_groups_is_not_moved_by_a_new_pose() {
fn models_in_a_shared_pose_posed_again_keep_their_sections() {
let presets = crate::default_presets_dir();
let open = |w: &World| gpu::Gpu::new().and_then(|g| LiveCore::new(g, w, Path::new(".."), &presets, 96, 54));
- let bend = |time| Some(crate::desc::Animation { clip: "bend".into(), time, r#loop: true });
+ let bend = |time| Some(crate::desc::Animation { clip: "bend".into(), time, r#loop: true, nodes: Default::default() });
let mut w = world();
for (id, x) in [(30, -0.7), (31, 0.7)] {
w.set_object(id, format!("arm{id}"), None, Kind::Model { uri: "tests/render/data/arm.glb".into(), nodes: None, animation: bend(0.0), functions: vec![] }, true, false).unwrap();
@@ -2141,6 +2141,42 @@ fn models_in_a_shared_pose_posed_again_keep_their_sections() {
assert!(apart(&a, &b) < 0.5, "the picture is {:.2} steps from a build's", apart(&a, &b));
}
+/// Models the game poses node by node (tests/render/data/arm.glb's joint `tip`, no clip): each is a pose of its own, even
+/// in the same pose as another, so posing them apart is in place; the picture is a build's.
+#[test]
+fn models_posed_node_by_node_are_posed_in_place() {
+ let presets = crate::default_presets_dir();
+ let open = |w: &World| gpu::Gpu::new().and_then(|g| LiveCore::new(g, w, Path::new(".."), &presets, 96, 54));
+ let turn = |a: f32| {
+ let q = glam::Quat::from_rotation_z(a);
+ Some(crate::desc::Animation { clip: String::new(), time: 0.0, r#loop: true, nodes: [("tip".to_string(), q.to_array().to_vec())].into() })
+ };
+ let mut w = world();
+ for (id, x) in [(30, -0.7), (31, 0.7)] {
+ w.set_object(id, format!("arm{id}"), None, Kind::Model { uri: "tests/render/data/arm.glb".into(), nodes: None, animation: turn(0.0), functions: vec![] }, true, false).unwrap();
+ w.set_transform(id, Vec3::new(x, -1.0, 0.8), glam::Quat::IDENTITY, Vec3::splat(2.0)).unwrap();
+ }
+ let mut live = match open(&w) {
+ Ok(c) => c,
+ Err(e) => return eprintln!("skipped: {e}"),
+ };
+ w.take_changes();
+ if !live.g.hwrt {
+ return eprintln!("skipped: no hardware ray tracing");
+ }
+ assert_eq!(live.sc.tables.retained.pose_groups.len(), 2, "each its own pose, though the same");
+ let before = picture(&mut live, 64);
+ for (id, a) in [(30, 0.9), (31, -1.2)] {
+ w.set_animation(id, turn(a)).unwrap();
+ }
+ assert!(!live.commit(&mut w).unwrap(), "posed apart in place ({:?})", live.fallback);
+ let mut fresh = open(&w).unwrap();
+ forget(&mut live);
+ let (a, b) = (picture(&mut live, 64), picture(&mut fresh, 64));
+ assert!(apart(&a, &b) < 0.5, "the picture is {:.2} steps from a build's", apart(&a, &b));
+ assert!(apart(&before, &a) > 0.5, "the new poses are in the picture ({:.2} steps)", apart(&before, &a));
+}
+
/// A scene whose only volume is hidden has its media passes made when it is loaded: the frame that shows the volume
/// compiles nothing (an idle fireball's first fire).
#[test]
diff --git a/renderer/src/scene.rs b/renderer/src/scene.rs
index e093824..615288f 100644
--- a/renderer/src/scene.rs
+++ b/renderer/src/scene.rs
@@ -964,8 +964,9 @@ pub struct PoseGroup {
pub members: Vec<(u32, u32)>,
}
-/// What groups posed models into a `PoseGroup`: model, nodes, clip, time (bits), loop.
-type PoseKey = (String, Option<Vec<String>>, String, u32, bool);
+/// What groups posed models into a `PoseGroup`: model, nodes, clip, time (bits), loop; for a model whose pose names
+/// nodes (posed by the game, its own), the object.
+type PoseKey = (String, Option<Vec<String>>, String, u32, bool, Option<u32>);
/// pathtrace.wgsl `Medium`: world -> local affine rows (the unit box / sphere's space), (function, shape or
/// `MEDIUM_HIDDEN`, homogeneous, animated),
@@ -1531,11 +1532,15 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
}
// (Copies with material functions share a pose only with the same functions: their own materials.)
let file = if functions.is_empty() { uri.clone() } else { format!("{uri}\u{0}{functions:?}") };
- let key: PoseKey = (file, nodes.clone(), a.clip.clone(), a.time.to_bits(), a.r#loop);
+ // A model the game poses node by node is a group of its own: its mesh (and BLAS) is skinned again when its
+ // pose changes, and moves as an instance, whatever the other models do (a player's body). It comes apart
+ // from no other, so no new pose rebuilds the scene.
+ let own = (!a.nodes.is_empty()).then_some(*id);
+ let key: PoseKey = (file, nodes.clone(), a.clip.clone(), a.time.to_bits(), a.r#loop, own);
*count.entry(key.clone()).or_default() += 1;
pose_key_of.insert(*id, key);
}
- pose_key_of.retain(|_, k| count[k] >= 2);
+ pose_key_of.retain(|_, k| count[k] >= 2 || k.5.is_some());
}
let mut pose_group_of: HashMap<PoseKey, Option<u32>> = HashMap::new();
// Flattened instances' triangle ranges.
@@ -1742,9 +1747,10 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
if instancing && posed && nodes.is_none() && glb.rigid() {
let a = animation.as_ref().unwrap();
let globals = glb.node_globals(Some(a))?;
- let pkey = (key.clone(), a.clip.clone());
+ // (What moves is the clip's nodes and the nodes the pose names.)
+ let pkey = (key.clone(), format!("{}\u{0}{}", a.clip, a.nodes.keys().cloned().collect::<Vec<_>>().join("\u{0}")));
if !rigid_parts.contains_key(&pkey) {
- let moving = glb.moving_nodes(&a.clip)?;
+ let moving = glb.moving_nodes(a)?;
// (THREERT_RIGID_NODES=all: no node merged, every one an instance of a mesh of its own: the A/B
// against the merged still part.)
let all = std::env::var("THREERT_RIGID_NODES").is_ok_and(|v| v == "all");
@@ -1876,8 +1882,9 @@ pub fn build(w: &World, assets: &Path, presets_dir: &Path, overrides: Option<&se
pool_attrs.push(section_attr(t.p, t.n, t.uv, t.tangent, section, rank));
}
let tri_order: Vec<(u32, u32, u32)> = order.iter().map(|&(k, section, rank)| (k as u32, section, rank)).collect();
- // Other poses reach further (a stride, a swing): object bounds a quarter wider each way.
- let pad = (hi - lo) * 0.25;
+ // Other poses reach further (a stride, a swing): object bounds a quarter wider each way;
+ // one the game poses may take any pose (lie down): as far as its size each way.
+ let pad = if key.5.is_some() { Vec3A::splat((hi - lo).length()) } else { (hi - lo) * 0.25 };
meshes.push(InstMesh { lo: lo - pad, hi: hi + pad, deforms: true, sect_first: sections.len() as u32, sect_count: sects.len() as u32, ..own_inst_mesh(&pool_tris[first as usize..], first) });
sections.extend(sects);
retained.mesh_rows.insert(meshes.len() as u32 - 1, mine);
@@ -2923,7 +2930,7 @@ mod instance_tests {
w.set_settings(world::Settings { camera: Some(9), ..Default::default() });
let model = |animation| Kind::Model { uri: "tests/render/data/panel-decal.glb".into(), nodes: None, animation, functions: vec![] };
w.set_object(1, "still".into(), None, model(None), true, false).unwrap();
- w.set_object(2, "posed".into(), None, model(Some(desc::Animation { clip: "slide".into(), time: 0.25, r#loop: true })), true, false).unwrap();
+ w.set_object(2, "posed".into(), None, model(Some(desc::Animation { clip: "slide".into(), time: 0.25, r#loop: true, nodes: Default::default() })), true, false).unwrap();
for id in [1, 2] {
w.set_transform(id, Vec3::new(id as f32, 0.0, 0.0), glam::Quat::from_rotation_y(0.4), Vec3::new(x, 1.0, 1.0)).unwrap();
}
@@ -3063,7 +3070,7 @@ mod instance_tests {
w.set_settings(world::Settings { camera: Some(9), ..Default::default() });
let model = |animation| Kind::Model { uri: "tests/render/data/panel-decal.glb".into(), nodes: None, animation, functions: vec![] };
w.set_object(1, "still".into(), None, model(None), true, false).unwrap();
- w.set_object(2, "posed".into(), None, model(Some(desc::Animation { clip: "slide".into(), time: 0.25, r#loop: true })), true, false).unwrap();
+ w.set_object(2, "posed".into(), None, model(Some(desc::Animation { clip: "slide".into(), time: 0.25, r#loop: true, nodes: Default::default() })), true, false).unwrap();
let sc = build(&w, Path::new(".."), &crate::default_presets_dir(), None).unwrap();
let mesh = |name: &str| {
let i = sc.instances.iter().find(|i| i.name == name).unwrap();
@@ -3090,7 +3097,7 @@ mod instance_tests {
w.set_object(9, "camera".into(), None, Kind::Camera(cam), true, false).unwrap();
w.set_settings(world::Settings { camera: Some(9), ..Default::default() });
for (id, time, movable) in [(1, 0.25, false), (2, 0.75, true)] {
- let animation = Some(desc::Animation { clip: "slide".into(), time, r#loop: true });
+ let animation = Some(desc::Animation { clip: "slide".into(), time, r#loop: true, nodes: Default::default() });
w.set_object(id, format!("model{id}"), None, Kind::Model { uri: "tests/render/data/panel-slider.glb".into(), nodes: None, animation, functions: vec![] }, true, movable).unwrap();
w.set_transform(id, Vec3::new(id as f32 * 20.0, 0.0, 0.0), glam::Quat::IDENTITY, Vec3::ONE).unwrap();
}
diff --git a/renderer/src/skin.rs b/renderer/src/skin.rs
index 28d81fc..db7e3f3 100644
--- a/renderer/src/skin.rs
+++ b/renderer/src/skin.rs
@@ -52,6 +52,8 @@ pub struct Model {
/// In the order the renderer emits them (depth first, as before posing existed).
prims: Vec<Prim>,
parents: Vec<Option<usize>>,
+ /// Nodes by name (the first of a name), for poses that name them (`desc::Animation::nodes`).
+ names: HashMap<String, usize>,
clips: Mutex<HashMap<String, Arc<Clip>>>,
}
@@ -109,7 +111,13 @@ impl Model {
});
}
}
- Ok(Model { gltf, prims, parents, clips: Mutex::new(HashMap::new()) })
+ let mut names = HashMap::new();
+ for n in doc.nodes() {
+ if let Some(name) = n.name() {
+ names.entry(name.to_string()).or_insert(n.index());
+ }
+ }
+ Ok(Model { gltf, prims, parents, names, clips: Mutex::new(HashMap::new()) })
}
/// Whether the file can be posed (has skins or animations).
@@ -163,7 +171,7 @@ impl Model {
(Vec3::from(t), Quat::from_array(r), Vec3::from(s))
})
.collect();
- if let Some(a) = pose {
+ if let Some(a) = pose.filter(|a| !a.clip.is_empty()) {
let clip = self.clip(&a.clip)?;
let t = if clip.duration <= 0.0 { 0.0 } else if a.r#loop { a.time.rem_euclid(clip.duration) } else { a.time.clamp(0.0, clip.duration) };
for ch in &clip.channels {
@@ -176,6 +184,24 @@ impl Model {
}
}
}
+ // The nodes the game poses itself, over the clip.
+ for (name, v) in pose.map(|a| &a.nodes).into_iter().flatten() {
+ let &i = self.names.get(name).ok_or_else(|| anyhow!("pose: no node \"{name}\""))?;
+ let (t, r) = match v.len() {
+ 4 => (None, [v[0], v[1], v[2], v[3]]),
+ 7 => (Some(Vec3::new(v[0], v[1], v[2])), [v[3], v[4], v[5], v[6]]),
+ n => return Err(anyhow!("pose: node \"{name}\" has {n} numbers (4: a rotation, 7: a translation and a rotation)")),
+ };
+ let q = Quat::from_array(r);
+ if !q.is_finite() || q.length_squared() < 1e-12 || t.is_some_and(|t| !t.is_finite()) {
+ return Err(anyhow!("pose: node \"{name}\" is not a transform ({v:?})"));
+ }
+ let l = &mut local[i];
+ l.1 = q.normalize();
+ if let Some(t) = t {
+ l.0 = t;
+ }
+ }
let mut global: Vec<Option<Mat4>> = vec![None; local.len()];
fn resolve(i: usize, local: &[(Vec3, Quat, Vec3)], parents: &[Option<usize>], global: &mut Vec<Option<Mat4>>) -> Mat4 {
if let Some(m) = global[i] {
@@ -198,12 +224,16 @@ impl Model {
self.prims.iter().all(|p| p.skin.is_none())
}
- /// Per node: whether clip `clip` moves it (a channel targets it or one of its ancestors).
- pub fn moving_nodes(&self, clip: &str) -> Result<Vec<bool>> {
- let c = self.clip(clip)?;
+ /// Per node: whether the pose moves it (a channel of its clip or a node it poses is it or one of its ancestors).
+ pub fn moving_nodes(&self, pose: &desc::Animation) -> Result<Vec<bool>> {
let mut direct = vec![false; self.parents.len()];
- for ch in &c.channels {
- direct[ch.node] = true;
+ if !pose.clip.is_empty() {
+ for ch in &self.clip(&pose.clip)?.channels {
+ direct[ch.node] = true;
+ }
+ }
+ for name in pose.nodes.keys() {
+ direct[*self.names.get(name).ok_or_else(|| anyhow!("pose: no node \"{name}\""))?] = true;
}
Ok((0..self.parents.len())
.map(|i| {
@@ -371,8 +401,8 @@ mod tests {
fn rigid_split_moves_the_animated_subtree() {
let m = Model::new(gltf::import_slice(RIGID.as_bytes()).unwrap()).unwrap();
assert!(m.rigid());
- assert_eq!(m.moving_nodes("move").unwrap(), vec![true, true, false]);
- let pose = desc::Animation { clip: "move".into(), time: 0.5, r#loop: false };
+ let pose = desc::Animation { clip: "move".into(), time: 0.5, r#loop: false, nodes: Default::default() };
+ assert_eq!(m.moving_nodes(&pose).unwrap(), vec![true, true, false]);
let g = m.node_globals(Some(&pose)).unwrap();
assert!((g[1].transform_point3(Vec3::ZERO) - Vec3::new(1.0, 1.0, 0.0)).length() < 1e-6);
// Static part in world space (the object at x = 10), the moving part in its node's space.
@@ -408,6 +438,30 @@ mod tests {
assert!(m.node_triangles(Mat4::IDENTITY, None, &|_| true, true).unwrap().iter().all(|(_, t)| hand(t) == 1.0));
}
+ #[test]
+ fn nodes_posed_by_name_over_the_clip() {
+ let m = Model::new(gltf::import_slice(RIGID.as_bytes()).unwrap()).unwrap();
+ let q = Quat::from_rotation_z(std::f32::consts::FRAC_PI_2);
+ // A rotation over the clip's translation; a translation and a rotation; a node the clip does not move.
+ let pose = |nodes: &[(&str, Vec<f32>)]| desc::Animation { clip: "move".into(), time: 0.5, r#loop: false, nodes: nodes.iter().map(|(k, v)| (k.to_string(), v.clone())).collect() };
+ let g = m.node_globals(Some(&pose(&[("arm", q.to_array().to_vec())]))).unwrap();
+ assert!((g[1].transform_point3(Vec3::ZERO) - Vec3::new(0.0, 2.0, 0.0)).length() < 1e-5, "hand turned about the arm, the arm where the clip has it");
+ let mut tr = vec![3.0, 0.0, 0.0];
+ tr.extend(Quat::IDENTITY.to_array());
+ let g = m.node_globals(Some(&pose(&[("arm", tr), ("base", q.to_array().to_vec())]))).unwrap();
+ assert!((g[1].transform_point3(Vec3::ZERO) - Vec3::new(4.0, 0.0, 0.0)).length() < 1e-5, "the translation replaces the clip's");
+ assert!((g[2].transform_point3(Vec3::X) - Vec3::new(0.0, 1.0, 5.0)).length() < 1e-5);
+ let a = pose(&[("base", q.to_array().to_vec())]);
+ assert_eq!(m.moving_nodes(&a).unwrap(), vec![true, true, true], "a posed node moves");
+ // Without a clip: the file's transforms and the named nodes.
+ let a = desc::Animation { clip: String::new(), time: 0.0, r#loop: true, nodes: [("arm".to_string(), q.to_array().to_vec())].into() };
+ assert!((m.node_globals(Some(&a)).unwrap()[1].transform_point3(Vec3::ZERO) - Vec3::new(0.0, 1.0, 0.0)).length() < 1e-5);
+ assert_eq!(m.moving_nodes(&a).unwrap(), vec![true, true, false]);
+ assert!(m.node_globals(Some(&pose(&[("elbow", q.to_array().to_vec())]))).is_err(), "no such node");
+ assert!(m.node_globals(Some(&pose(&[("arm", vec![0.0, 0.0, 0.0])]))).is_err(), "3 numbers");
+ assert!(m.node_globals(Some(&pose(&[("arm", vec![0.0; 4])]))).is_err(), "not a rotation");
+ }
+
fn ch(interpolation: gltf::animation::Interpolation, path: Path, times: Vec<f32>, values: Vec<[f32; 4]>) -> Channel {
Channel { node: 0, path, interpolation, times, values }
}
@@ -443,11 +497,11 @@ mod bench {
let t0 = web_time::Instant::now();
let mut n = 0;
for k in 0..100 {
- let a = crate::desc::Animation { clip: clip.clone(), time: k as f32 * 0.016, r#loop: true };
+ let a = crate::desc::Animation { clip: clip.clone(), time: k as f32 * 0.016, r#loop: true, nodes: Default::default() };
n = m.triangles(glam::Mat4::IDENTITY, None, Some(&a)).unwrap().len();
}
eprintln!("{n} triangles: {:.3} ms per pose", t0.elapsed().as_secs_f64() * 1000.0 / 100.0);
- let a = crate::desc::Animation { clip, time: 0.3, r#loop: true };
+ let a = crate::desc::Animation { clip, time: 0.3, r#loop: true, nodes: Default::default() };
let tris = m.triangles(glam::Mat4::IDENTITY, None, Some(&a)).unwrap();
let t0 = web_time::Instant::now();
let mut x = 0.0;
diff --git a/tools/three/engine.ts b/tools/three/engine.ts
index d5e1bc5..e03e303 100644
--- a/tools/three/engine.ts
+++ b/tools/three/engine.ts
@@ -648,14 +648,30 @@ export class ThreeEngine implements Engine {
if (!root || !clips) return;
if (!n.mixer) n.mixer = new THREE.AnimationMixer(root);
n.mixer.stopAllAction();
+ // Nodes the last pose named go back to the file's transforms first.
+ const rest = (root.userData.rest ??= new Map()) as Map<THREE.Object3D, [THREE.Vector3, THREE.Quaternion]>;
+ for (const [o, [p, q]] of rest) {
+ o.position.copy(p);
+ o.quaternion.copy(q);
+ }
if (!n.anim) return;
- const clip = THREE.AnimationClip.findByName(clips, n.anim.clip);
- if (!clip) throw new Error(`${n.desc.name}: no animation clip "${n.anim.clip}" (has ${clips.map((c) => c.name).join(", ")})`);
- const action = n.mixer.clipAction(clip);
- action.setLoop(n.anim.loop ? THREE.LoopRepeat : THREE.LoopOnce, Infinity);
- action.clampWhenFinished = true;
- action.play();
- n.mixer.setTime(n.anim.time);
+ if (n.anim.clip) {
+ const clip = THREE.AnimationClip.findByName(clips, n.anim.clip);
+ if (!clip) throw new Error(`${n.desc.name}: no animation clip "${n.anim.clip}" (has ${clips.map((c) => c.name).join(", ")})`);
+ const action = n.mixer.clipAction(clip);
+ action.setLoop(n.anim.loop ? THREE.LoopRepeat : THREE.LoopOnce, Infinity);
+ action.clampWhenFinished = true;
+ action.play();
+ n.mixer.setTime(n.anim.time);
+ }
+ for (const [name, v] of Object.entries(n.anim.nodes ?? {})) {
+ const o = root.getObjectByName(name);
+ if (!o) throw new Error(`${n.desc.name}: animation: no node "${name}"`);
+ if (!rest.has(o)) rest.set(o, [o.position.clone(), o.quaternion.clone()]);
+ if (v.length === 7) o.position.set(v[0]!, v[1]!, v[2]!);
+ const r = v.length === 7 ? 3 : 0;
+ o.quaternion.set(v[r]!, v[r + 1]!, v[r + 2]!, v[r + 3]!).normalize();
+ }
}
// ---------------------------------------------------------------------------------------------- lights