Skip to main content

concinnity_core/components/
skinned_mesh.rs

1// src/components/skinned_mesh.rs
2//
3// Runtime behavior for the SkinnedMesh asset. The authored schema (SkinnedMesh,
4// its SkinnedVertexData / SkeletonJoint / CharacterCapsule, and their Defaults) lives
5// above; SkinnedMesh is a resource (compiled by cook into the
6// blob's resource stream, no `Component` impl), so this file keeps only the
7// skeleton builder and the `SkinnedMeshGeometry` extension trait that needs
8// `gfx::skeleton`.
9
10use crate::ecs::MaterialHandle;
11use crate::ecs::PayloadLocator;
12use crate::ecs::TextureHandle;
13use crate::ecs::asset_id::AssetId;
14use crate::ecs::de_opt_material_handle;
15use crate::ecs::de_opt_texture_handle;
16use alloc::string::String;
17use alloc::vec::Vec;
18
19fn white() -> [f32; 3] {
20    [1.0, 1.0, 1.0]
21}
22
23fn first_weight() -> [f32; 4] {
24    [1.0, 0.0, 0.0, 0.0]
25}
26
27/// One vertex of a skinned mesh. Beyond position / colour / uv it carries up
28/// to four joint bindings: `joints[k]` indexes the skeleton, `weights[k]` is
29/// its blend weight. Weights are normalised at build time.
30#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
31pub struct SkinnedVertexData {
32    /// Vertex position `[x, y, z]` in model space.
33    pub pos: [f32; 3],
34    /// Vertex colour `[r, g, b]` in [0, 1]. Defaults to white.
35    #[serde(default = "white")]
36    pub color: [f32; 3],
37    /// Texture coordinates in [0, 1] space. Defaults to [0, 0].
38    #[serde(default)]
39    pub uv: [f32; 2],
40    /// Joint indices this vertex is bound to. Unused slots can be 0.
41    #[serde(default)]
42    pub joints: [u32; 4],
43    /// Blend weights parallel to `joints`. Defaults to fully bound to joint 0.
44    #[serde(default = "first_weight")]
45    pub weights: [f32; 4],
46}
47
48/// One morph-target vertex delta: offsets added to the bind-pose position and
49/// normal, scaled by the target's weight at runtime.
50#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize)]
51#[serde(default)]
52pub struct MorphDelta {
53    /// Position offset `[x, y, z]` in model space.
54    pub position: [f32; 3],
55    /// Normal offset; the deformed normal is re-normalised after adding it.
56    pub normal: [f32; 3],
57}
58
59/// One joint of a skeleton's bind pose.
60#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
61#[serde(default)]
62pub struct SkeletonJoint {
63    /// Human-readable joint name (animation tracks may reference it later).
64    pub name: String,
65    /// Parent joint index, or -1 for a root. Parents must appear before their
66    /// children in the `skeleton` list.
67    pub parent: i32,
68    /// Local bind translation relative to the parent.
69    pub translation: [f32; 3],
70    /// Local bind rotation, Euler degrees [pitch, yaw, roll], YXZ order.
71    pub rotation_deg: [f32; 3],
72    /// Local bind scale.
73    pub scale: [f32; 3],
74}
75
76impl Default for SkeletonJoint {
77    fn default() -> Self {
78        Self {
79            name: String::new(),
80            parent: -1,
81            translation: [0.0, 0.0, 0.0],
82            rotation_deg: [0.0, 0.0, 0.0],
83            scale: [1.0, 1.0, 1.0],
84        }
85    }
86}
87
88/// A skeletally animated mesh placed directly in the world.
89///
90/// Unlike a [Mesh](#mesh), a `SkinnedMesh` carries its own world transform and a
91/// `skeleton` (a joint hierarchy with a bind pose). Each vertex is bound to up
92/// to four joints; an [Animation](#animation) targeting this mesh deforms it at
93/// runtime. With no animation the mesh renders in its bind pose.
94///
95/// The geometry + skeleton may be authored inline (`vertices` / `indices` /
96/// `skeleton`) or imported with `source` from a glTF (`.glb` / `.gltf`) or
97/// binary `.fbx` file. The import fills the mesh, the skeleton bind pose,
98/// and (for glTF) any morph targets; animations are imported separately by
99/// [Animation](#animation) assets referencing the same file.
100///
101/// The `customize_character` example ships a neutral unclothed body
102/// (`base_humanoid.glb`, about 19k vertices, A-pose bind) with a 25-joint
103/// skeleton (`root`, `hips`, `spine`, `chest`,
104/// `upper_chest`, `neck`, `head`, and `clavicle` / `upper_arm` / `forearm` /
105/// `hand` / `thumb` / `thigh` / `shin` / `foot` / `toe` with an `_l` / `_r`
106/// suffix), the morph targets a [CharacterShape](#charactershape) slider set
107/// names (`weight+/-`, `muscle`, `shoulders+/-`, `hips+/-`, `chest+/-`,
108/// `belly`, `head+/-`, `jaw+/-`, `nose+/-`, `brow`, `cheeks+/-`,
109/// `chin+/-`), and a rotation-only `idle` clip an Animation can import from
110/// the same file; a [CharacterModel](#charactermodel) is the usual way to
111/// declare it.
112///
113/// The `skeleton` (joint hierarchy and bind pose) is provided as an arg
114/// (authored inline alongside `vertices`/`indices`, or filled in from the
115/// imported `.glb`) and is baked into the mesh at build time.
116///
117/// Normals and tangents are computed automatically at build time. Do not
118/// supply them.
119///
120/// ```rust
121/// # use concinnity_core::components::SkinnedMesh;
122/// SkinnedMesh {
123///     position: [0.0, 1.0, 0.0],
124///     ..Default::default()
125/// };
126/// ```
127#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)]
128#[serde(default)]
129pub struct SkinnedMesh {
130    /// Asset identity; injected via `inject_name`. Not part of `args`.
131    #[serde(skip)]
132    pub asset_id: AssetId,
133    /// Optional path to a `.glb` / `.gltf` / `.fbx` file. When set, the
134    /// build imports `vertices` / `indices` / `skeleton` from it; an
135    /// inline-authored mesh leaves this empty.
136    pub source: String,
137    /// Which skinned mesh of `source` to import, in file declaration order
138    /// (default 0). A character split into several meshes bound to one
139    /// skeleton (body, hair, clothes) needs one `SkinnedMesh` per part, each
140    /// naming its own index.
141    pub skin_index: u32,
142    /// Skinned vertex list.
143    pub vertices: Vec<SkinnedVertexData>,
144    /// Triangle index list.
145    pub indices: Vec<u16>,
146    /// Morph-target names, one per target, in target order. Filled from the
147    /// source file's target names when importing; empty for a mesh without
148    /// morph targets.
149    pub morph_target_names: Vec<String>,
150    /// Dense morph-target deltas, target-major: entry `t * vertex_count + v`
151    /// is target `t`'s delta for vertex `v`. Length must be
152    /// `morph_target_names.len() * vertices.len()`. An [Animation](#animation)
153    /// with a `morph_track` drives the per-target weights at runtime.
154    pub morph_deltas: Vec<MorphDelta>,
155    /// [Material](#material); provides the albedo texture plus lighting
156    /// parameters.
157    #[serde(deserialize_with = "de_opt_material_handle")]
158    pub material: Option<MaterialHandle>,
159    /// [Texture](#texture) (older path); ignored when `material` is set.
160    #[serde(deserialize_with = "de_opt_texture_handle")]
161    pub texture: Option<TextureHandle>,
162    /// World-space position.
163    pub position: [f32; 3],
164    /// World rotation, Euler degrees [pitch, yaw, roll], YXZ order.
165    pub rotation_deg: [f32; 3],
166    /// World scale.
167    pub scale: [f32; 3],
168    /// Number of level-of-detail versions to generate, including the original.
169    /// `1` (the default) generates none; values are clamped to `[1, 8]`.
170    pub lod_levels: u32,
171    /// Camera distances at which to switch to each lower-detail version. When
172    /// non-empty, must have exactly `lod_levels - 1` entries; empty lets the
173    /// build choose defaults.
174    #[serde(default)]
175    pub lod_distances: Vec<f32>,
176    /// How many runtime copies of this mesh may exist at once beyond the
177    /// authored one. `0` (the default) means the mesh is not runtime-spawnable.
178    /// A non-zero value pre-reserves that many extra instance slots at load: the
179    /// engine appends that many hidden bind-pose copies to the skinned geometry
180    /// so a runtime spawn can claim one without growing any GPU buffer, and a
181    /// despawn returns it to the pool. Spawns past the reserve are dropped (a
182    /// warning is logged). Capped at 4096.
183    pub max_instances: u32,
184    /// Optional character capsule. When set, the mesh collides with the
185    /// scene as a kinematic character and is moved by the root motion of its
186    /// [Animation](#animation) clips (those with `root_motion` set): the
187    /// capsule slides along obstacles and settles under gravity, and the
188    /// rendered mesh follows it. The capsule stands on the mesh origin (its
189    /// feet), centred `half_height + radius` above it.
190    pub capsule: Option<CharacterCapsule>,
191    /// Injected at load time from the compiled blob payload.
192    #[serde(skip)]
193    pub locator: Option<PayloadLocator>,
194}
195
196/// A kinematic character capsule for a [SkinnedMesh](#skinnedmesh), in world
197/// units (after the mesh's `scale`).
198#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
199#[serde(default)]
200pub struct CharacterCapsule {
201    /// Half-height of the capsule's cylindrical section.
202    pub half_height: f32,
203    /// Capsule radius.
204    pub radius: f32,
205}
206
207impl Default for CharacterCapsule {
208    fn default() -> Self {
209        Self {
210            half_height: 0.5,
211            radius: 0.3,
212        }
213    }
214}
215
216#[cfg(test)]
217mod tests {
218    use super::*;
219    use alloc::vec;
220
221    #[test]
222    fn a_vertex_with_only_a_position_binds_fully_to_its_first_joint() {
223        // Importers emit position-only vertices for unweighted geometry; the
224        // defaults have to make that render white and rigid rather than black
225        // and collapsed to the origin.
226        let v: SkinnedVertexData = serde_json::from_str(r#"{"pos":[1,2,3]}"#).unwrap();
227        assert_eq!(v.pos, [1.0, 2.0, 3.0]);
228        assert_eq!(v.color, [1.0, 1.0, 1.0]);
229        assert_eq!(v.uv, [0.0, 0.0]);
230        assert_eq!(v.joints, [0, 0, 0, 0]);
231        assert_eq!(v.weights, [1.0, 0.0, 0.0, 0.0]);
232    }
233
234    #[test]
235    fn a_weighted_vertex_keeps_its_authored_joints_and_weights() {
236        let v: SkinnedVertexData = serde_json::from_str(
237            r#"{"pos":[0,0,0],"color":[0.5,0.5,0.5],"uv":[0.25,0.75],
238                "joints":[3,4,0,0],"weights":[0.6,0.4,0,0]}"#,
239        )
240        .unwrap();
241        assert_eq!(v.color, [0.5, 0.5, 0.5]);
242        assert_eq!(v.uv, [0.25, 0.75]);
243        assert_eq!(v.joints, [3, 4, 0, 0]);
244        assert_eq!(v.weights, [0.6, 0.4, 0.0, 0.0]);
245    }
246
247    #[test]
248    fn a_blank_joint_is_a_root_at_the_bind_pose_origin() {
249        let j = SkeletonJoint::default();
250        assert!(j.name.is_empty());
251        // -1 is the root marker; 0 would make every joint a child of joint 0.
252        assert_eq!(j.parent, -1);
253        assert_eq!(j.translation, [0.0, 0.0, 0.0]);
254        assert_eq!(j.scale, [1.0, 1.0, 1.0]);
255    }
256
257    #[test]
258    fn a_blank_morph_delta_moves_nothing() {
259        let d = MorphDelta::default();
260        assert_eq!(
261            d,
262            MorphDelta {
263                position: [0.0; 3],
264                normal: [0.0; 3],
265            }
266        );
267    }
268
269    #[test]
270    fn a_blank_mesh_has_no_geometry_and_no_capsule() {
271        let m = SkinnedMesh::default();
272        assert!(m.vertices.is_empty());
273        assert!(m.indices.is_empty());
274        assert!(m.morph_target_names.is_empty());
275        assert!(m.capsule.is_none());
276        assert!(m.locator.is_none());
277        assert_eq!(m.scale, [0.0, 0.0, 0.0]);
278        let c = CharacterCapsule::default();
279        assert_eq!((c.half_height, c.radius), (0.5, 0.3));
280    }
281
282    #[test]
283    fn an_imported_mesh_round_trips_through_postcard() {
284        crate::test_support::install_resolvers();
285        let m: SkinnedMesh = serde_json::from_str(
286            r#"{"source":"hero.glb","skin_index":1,"material":"skin_mat","texture":"skin_tex",
287                "vertices":[{"pos":[0,0,0]}],"indices":[0],
288                "morph_target_names":["smile"],"morph_deltas":[{"position":[0,0.1,0]}],
289                "position":[1,0,2],"scale":[1,1,1],"lod_levels":2,"lod_distances":[10],
290                "max_instances":4,"capsule":{"half_height":0.9,"radius":0.35}}"#,
291        )
292        .unwrap();
293        assert_eq!(m.material, Some(MaterialHandle(8)));
294        assert_eq!(m.texture, Some(TextureHandle(8)));
295        assert_eq!(m.morph_target_names, ["smile"]);
296
297        let bytes = postcard::to_allocvec(&m).unwrap();
298        let back: SkinnedMesh = postcard::from_bytes(&bytes).unwrap();
299        assert_eq!(back.source, "hero.glb");
300        assert_eq!(back.skin_index, 1);
301        assert_eq!(back.vertices[0].weights, [1.0, 0.0, 0.0, 0.0]);
302        assert_eq!(
303            back.morph_deltas,
304            vec![MorphDelta {
305                position: [0.0, 0.1, 0.0],
306                normal: [0.0; 3],
307            }]
308        );
309        assert_eq!(back.lod_distances, [10.0]);
310        assert_eq!(back.max_instances, 4);
311        assert_eq!(back.capsule.expect("capsule").half_height, 0.9);
312        // Identity and payload location are injected at load, never authored.
313        assert_eq!(back.asset_id, AssetId::default());
314        assert!(back.locator.is_none());
315    }
316}
317
318/// Build a runtime `Skeleton` from authored joint definitions. Mirrors the
319/// conversion `GraphicsSystem::init` does at world load time: each
320/// `SkeletonJoint.parent` becomes `Some(usize)` for valid indices (negative values
321/// mark roots), and each `SkeletonJoint`'s translation / rotation / scale becomes the
322/// joint's bind `JointPose`. Used at init and by the asset hot-reload's
323/// skeleton-shape change path.
324pub fn build_skeleton_from_joint_defs(defs: &[SkeletonJoint]) -> crate::gfx::skeleton::Skeleton {
325    use crate::gfx::skeleton as skinning;
326    let joints = defs
327        .iter()
328        .map(|jd| skinning::Joint {
329            name: jd.name.clone(),
330            parent: (jd.parent >= 0).then_some(jd.parent as usize),
331            bind: skinning::JointPose {
332                translation: jd.translation,
333                rotation_deg: jd.rotation_deg,
334                scale: jd.scale,
335            },
336        })
337        .collect();
338    skinning::Skeleton::new(joints)
339}
340
341/// Column-major world matrix from a SkinnedMesh's transform. Kept in core (not
342/// the schema half) because the matrix build goes through `gfx::skeleton`, which
343/// needs std transcendentals. Exposed as an extension trait so call sites keep
344/// method syntax (`sm.model_matrix()`), matching `geometry.rs`.
345pub trait SkinnedMeshGeometry {
346    /// Column-major world matrix built from the mesh's transform.
347    fn model_matrix(&self) -> [[f32; 4]; 4];
348}
349
350impl SkinnedMeshGeometry for SkinnedMesh {
351    // Same construction order (scale, YXZ rotation, translate) as
352    // `Prop::model_matrix`.
353    fn model_matrix(&self) -> [[f32; 4]; 4] {
354        crate::gfx::skeleton::JointPose {
355            translation: self.position,
356            rotation_deg: self.rotation_deg,
357            scale: self.scale,
358        }
359        .to_matrix()
360    }
361}
362
363#[cfg(test)]
364mod runtime_tests {
365    use super::*;
366    use crate::components::{CharacterCapsule, SkinnedVertexData};
367    use alloc::vec;
368
369    #[test]
370    fn build_skeleton_from_joint_defs_preserves_count_and_parent_links() {
371        let defs = vec![
372            SkeletonJoint {
373                name: "root".into(),
374                parent: -1,
375                translation: [0.0, 0.0, 0.0],
376                rotation_deg: [0.0, 0.0, 0.0],
377                scale: [1.0, 1.0, 1.0],
378            },
379            SkeletonJoint {
380                name: "tip".into(),
381                parent: 0,
382                translation: [0.0, 1.0, 0.0],
383                rotation_deg: [0.0, 0.0, 0.0],
384                scale: [1.0, 1.0, 1.0],
385            },
386            SkeletonJoint {
387                name: "tail".into(),
388                parent: 1,
389                translation: [0.0, 1.0, 0.0],
390                rotation_deg: [0.0, 0.0, 0.0],
391                scale: [1.0, 1.0, 1.0],
392            },
393        ];
394        let skel = build_skeleton_from_joint_defs(&defs);
395        assert_eq!(skel.len(), 3);
396        let joints = skel.joints();
397        assert_eq!(joints[0].parent, None);
398        assert_eq!(joints[1].parent, Some(0));
399        assert_eq!(joints[2].parent, Some(1));
400    }
401
402    #[test]
403    fn build_skeleton_from_joint_defs_treats_negative_parent_as_root() {
404        // Any negative parent (not just -1) collapses to None; mirrors the
405        // init-time semantics so a hot-reload from the same SkeletonJoint shape
406        // produces the same Skeleton.
407        let defs = vec![SkeletonJoint {
408            name: "root".into(),
409            parent: -42,
410            translation: [1.0, 2.0, 3.0],
411            rotation_deg: [0.0, 0.0, 0.0],
412            scale: [1.0, 1.0, 1.0],
413        }];
414        let skel = build_skeleton_from_joint_defs(&defs);
415        assert_eq!(skel.joints()[0].parent, None);
416    }
417
418    #[test]
419    fn model_matrix_places_translation_in_last_column() {
420        let mesh = SkinnedMesh {
421            position: [2.0, 3.0, 4.0],
422            scale: [1.0, 1.0, 1.0],
423            ..SkinnedMesh::default()
424        };
425        let m = mesh.model_matrix();
426        // Column-major: the translation lives in the last column, identity
427        // scale keeps the diagonal at 1.
428        assert_eq!([m[3][0], m[3][1], m[3][2]], [2.0, 3.0, 4.0]);
429        assert_eq!(m[3][3], 1.0);
430        assert_eq!(m[0][0], 1.0);
431    }
432
433    #[test]
434    fn skinned_vertex_defaults_fill_color_uv_and_weights() {
435        // A vertex authored with only a position picks up the serde defaults:
436        // white colour, zero uv, and full weight on joint 0.
437        let v: SkinnedVertexData =
438            serde_json::from_value(serde_json::json!({"pos": [0.0, 0.0, 0.0]})).unwrap();
439        assert_eq!(v.color, [1.0, 1.0, 1.0]);
440        assert_eq!(v.uv, [0.0, 0.0]);
441        assert_eq!(v.weights, [1.0, 0.0, 0.0, 0.0]);
442        assert_eq!(v.joints, [0, 0, 0, 0]);
443    }
444
445    #[test]
446    fn capsule_joint_defaults() {
447        let cap = CharacterCapsule::default();
448        assert_eq!(cap.half_height, 0.5);
449        assert_eq!(cap.radius, 0.3);
450
451        let jd: SkeletonJoint = serde_json::from_value(serde_json::json!({})).unwrap();
452        assert_eq!(jd.parent, -1);
453        assert_eq!(jd.scale, [1.0, 1.0, 1.0]);
454    }
455}