vrm-runtime 0.1.0

Renderer-agnostic VRM 1.0 loader, validator, animation system, and runtime
Documentation
use glam::Mat4;

/// A glTF skin: the joint nodes and their inverse bind matrices used to
/// compute the joint matrices for GPU skinning.
#[derive(Debug, Clone)]
pub struct Skin {
    joints: Vec<u32>,
    inverse_bind_matrices: Vec<Mat4>,
}

impl Skin {
    /// Creates a skin from joint node indices and matching inverse bind matrices.
    ///
    /// Cross-object validation occurs when the containing asset is built.
    pub fn new(joints: Vec<u32>, inverse_bind_matrices: Vec<Mat4>) -> Self {
        Self {
            joints,
            inverse_bind_matrices,
        }
    }

    /// Returns the avatar node index for each joint palette entry.
    pub fn joints(&self) -> &[u32] {
        &self.joints
    }

    /// Returns the inverse bind matrix corresponding to each joint.
    pub fn inverse_bind_matrices(&self) -> &[Mat4] {
        &self.inverse_bind_matrices
    }
}

pub(crate) fn load_skins(
    doc: &gltf::Document,
    buffers: &[gltf::buffer::Data],
) -> Result<Vec<Skin>, crate::LoadError> {
    doc.skins()
        .map(|skin| {
            let joints: Vec<u32> = skin.joints().map(|n| n.index() as u32).collect();

            let reader = skin.reader(|buffer| Some(buffers[buffer.index()].0.as_slice()));
            let mut inverse_bind_matrices = match reader.read_inverse_bind_matrices() {
                Some(matrices) => matrices.map(|m| Mat4::from_cols_array_2d(&m)).collect(),
                None => vec![Mat4::IDENTITY; joints.len()],
            };
            if inverse_bind_matrices.len() < joints.len() {
                return Err(crate::LoadError::InvalidVrm(format!(
                    "skin {} has {} joints but only {} inverse bind matrices",
                    skin.index(),
                    joints.len(),
                    inverse_bind_matrices.len()
                )));
            }
            if inverse_bind_matrices
                .iter()
                .flat_map(|matrix| matrix.to_cols_array())
                .any(|value| !value.is_finite())
            {
                return Err(crate::LoadError::InvalidVrm(format!(
                    "skin {} contains a non-finite inverse bind matrix",
                    skin.index()
                )));
            }
            // glTF permits extra accessor elements; renderer-facing data keeps
            // exactly the matrices that correspond to declared joints.
            inverse_bind_matrices.truncate(joints.len());

            Ok(Skin::new(joints, inverse_bind_matrices))
        })
        .collect()
}