vrm-runtime 0.1.0

Renderer-agnostic VRM 1.0 loader, validator, animation system, and runtime
Documentation
use crate::node::AvatarNode;
use crate::{
    Avatar, AvatarAsset, AvatarImage, AvatarMeta, AvatarTexture, BuildError, Expressions,
    FirstPerson, Humanoid, LookAt, Material, NodeConstraint, RenderPrimitive, Skin, SpringBone,
};

/// Builds a programmatic avatar and validates it before it becomes immutable.
#[derive(Debug)]
pub struct AvatarAssetBuilder {
    asset: Avatar,
}

impl AvatarAssetBuilder {
    /// Creates an empty asset builder.
    ///
    /// [`Self::build`] requires complete VRM metadata, a valid humanoid, and
    /// the corresponding node hierarchy before it can succeed.
    pub fn new() -> Self {
        Self {
            asset: Avatar::new(),
        }
    }

    /// Replaces the required VRM metadata.
    pub fn with_meta(mut self, meta: AvatarMeta) -> Self {
        self.asset = self.asset.with_meta(meta);
        self
    }

    /// Replaces the humanoid bone-to-node mapping.
    pub fn with_humanoid(mut self, humanoid: Humanoid) -> Self {
        self.asset = self.asset.with_humanoid(humanoid);
        self
    }

    /// Replaces the preset and custom expression registry.
    pub fn with_expressions(mut self, expressions: Expressions) -> Self {
        self.asset = self.asset.with_expressions(expressions);
        self
    }

    /// Replaces the complete node hierarchy addressed by [`crate::NodeId`].
    pub fn with_nodes(mut self, nodes: Vec<AvatarNode>) -> Self {
        self.asset = self.asset.with_nodes(nodes);
        self
    }

    /// Replaces the renderer-ready primitive list.
    ///
    /// Use [`crate::RenderPrimitiveBuilder`] to construct each primitive
    /// without exposing storage indices or partially initialized buffers.
    pub fn with_primitives(mut self, primitives: Vec<RenderPrimitive>) -> Self {
        self.asset = self.asset.with_primitives(primitives);
        self
    }

    /// Replaces the encoded image list addressed by [`crate::ImageId`].
    pub fn with_images(mut self, images: Vec<AvatarImage>) -> Self {
        self.asset.images = images;
        self
    }

    /// Replaces the material list addressed by [`crate::MaterialId`].
    pub fn with_materials(mut self, materials: Vec<Material>) -> Self {
        self.asset.materials = materials;
        self
    }

    /// Replaces the texture list addressed by [`crate::TextureId`].
    pub fn with_textures(mut self, textures: Vec<AvatarTexture>) -> Self {
        self.asset.textures = textures;
        self
    }

    /// Replaces the skin list addressed by [`crate::SkinId`].
    pub fn with_skins(mut self, skins: Vec<Skin>) -> Self {
        self.asset.skins = skins;
        self
    }

    /// Adds the avatar's optional LookAt configuration.
    pub fn with_look_at(mut self, look_at: LookAt) -> Self {
        self.asset = self.asset.with_look_at(look_at);
        self
    }

    /// Replaces the first-person mesh visibility configuration.
    pub fn with_first_person(mut self, first_person: FirstPerson) -> Self {
        self.asset.first_person = first_person;
        self
    }

    /// Replaces the node-constraint list.
    pub fn with_constraints(mut self, constraints: Vec<NodeConstraint>) -> Self {
        self.asset = self.asset.with_node_constraints(constraints);
        self
    }

    /// Replaces the SpringBone collider and chain configuration.
    pub fn with_spring_bone(mut self, spring_bone: SpringBone) -> Self {
        self.asset = self.asset.with_spring_bone(spring_bone);
        self
    }

    /// Validates all object references and VRM invariants, then freezes the asset.
    pub fn build(self) -> Result<AvatarAsset, BuildError> {
        for (material_index, material) in self.asset.materials.iter().enumerate() {
            material
                .validate_programmatic(material_index, self.asset.textures.len())
                .map_err(BuildError::InvalidAsset)?;
        }
        for (primitive_index, primitive) in self.asset.primitives().iter().enumerate() {
            let Some(skin_index) = primitive.skin_index() else {
                continue;
            };
            let Some(skin) = self.asset.skins.get(skin_index) else {
                // The common asset validator reports the missing skin reference.
                continue;
            };
            let joint_count = skin.joints().len();
            let has_invalid_joint = primitive.skinning_sets().iter().any(|set| {
                set.joints()
                    .iter()
                    .zip(set.weights())
                    .any(|(joints, weights)| {
                        joints
                            .iter()
                            .zip(weights)
                            .any(|(&joint, &weight)| weight > 0.0 && joint as usize >= joint_count)
                    })
            });
            if has_invalid_joint {
                return Err(BuildError::InvalidAsset(format!(
                    "primitive {primitive_index} has a weighted joint outside skin {skin_index}"
                )));
            }
        }
        self.asset.validate_programmatic()?;
        Ok(self.asset)
    }
}

impl Default for AvatarAssetBuilder {
    fn default() -> Self {
        Self::new()
    }
}