Skip to main content

vrm_runtime/
builder.rs

1use crate::node::AvatarNode;
2use crate::{
3    Avatar, AvatarAsset, AvatarImage, AvatarMeta, AvatarTexture, BuildError, Expressions,
4    FirstPerson, Humanoid, LookAt, Material, NodeConstraint, RenderPrimitive, Skin, SpringBone,
5};
6
7/// Builds a programmatic avatar and validates it before it becomes immutable.
8#[derive(Debug)]
9pub struct AvatarAssetBuilder {
10    asset: Avatar,
11}
12
13impl AvatarAssetBuilder {
14    /// Creates an empty asset builder.
15    ///
16    /// [`Self::build`] requires complete VRM metadata, a valid humanoid, and
17    /// the corresponding node hierarchy before it can succeed.
18    pub fn new() -> Self {
19        Self {
20            asset: Avatar::new(),
21        }
22    }
23
24    /// Replaces the required VRM metadata.
25    pub fn with_meta(mut self, meta: AvatarMeta) -> Self {
26        self.asset = self.asset.with_meta(meta);
27        self
28    }
29
30    /// Replaces the humanoid bone-to-node mapping.
31    pub fn with_humanoid(mut self, humanoid: Humanoid) -> Self {
32        self.asset = self.asset.with_humanoid(humanoid);
33        self
34    }
35
36    /// Replaces the preset and custom expression registry.
37    pub fn with_expressions(mut self, expressions: Expressions) -> Self {
38        self.asset = self.asset.with_expressions(expressions);
39        self
40    }
41
42    /// Replaces the complete node hierarchy addressed by [`crate::NodeId`].
43    pub fn with_nodes(mut self, nodes: Vec<AvatarNode>) -> Self {
44        self.asset = self.asset.with_nodes(nodes);
45        self
46    }
47
48    /// Replaces the renderer-ready primitive list.
49    ///
50    /// Use [`crate::RenderPrimitiveBuilder`] to construct each primitive
51    /// without exposing storage indices or partially initialized buffers.
52    pub fn with_primitives(mut self, primitives: Vec<RenderPrimitive>) -> Self {
53        self.asset = self.asset.with_primitives(primitives);
54        self
55    }
56
57    /// Replaces the encoded image list addressed by [`crate::ImageId`].
58    pub fn with_images(mut self, images: Vec<AvatarImage>) -> Self {
59        self.asset.images = images;
60        self
61    }
62
63    /// Replaces the material list addressed by [`crate::MaterialId`].
64    pub fn with_materials(mut self, materials: Vec<Material>) -> Self {
65        self.asset.materials = materials;
66        self
67    }
68
69    /// Replaces the texture list addressed by [`crate::TextureId`].
70    pub fn with_textures(mut self, textures: Vec<AvatarTexture>) -> Self {
71        self.asset.textures = textures;
72        self
73    }
74
75    /// Replaces the skin list addressed by [`crate::SkinId`].
76    pub fn with_skins(mut self, skins: Vec<Skin>) -> Self {
77        self.asset.skins = skins;
78        self
79    }
80
81    /// Adds the avatar's optional LookAt configuration.
82    pub fn with_look_at(mut self, look_at: LookAt) -> Self {
83        self.asset = self.asset.with_look_at(look_at);
84        self
85    }
86
87    /// Replaces the first-person mesh visibility configuration.
88    pub fn with_first_person(mut self, first_person: FirstPerson) -> Self {
89        self.asset.first_person = first_person;
90        self
91    }
92
93    /// Replaces the node-constraint list.
94    pub fn with_constraints(mut self, constraints: Vec<NodeConstraint>) -> Self {
95        self.asset = self.asset.with_node_constraints(constraints);
96        self
97    }
98
99    /// Replaces the SpringBone collider and chain configuration.
100    pub fn with_spring_bone(mut self, spring_bone: SpringBone) -> Self {
101        self.asset = self.asset.with_spring_bone(spring_bone);
102        self
103    }
104
105    /// Validates all object references and VRM invariants, then freezes the asset.
106    pub fn build(self) -> Result<AvatarAsset, BuildError> {
107        for (material_index, material) in self.asset.materials.iter().enumerate() {
108            material
109                .validate_programmatic(material_index, self.asset.textures.len())
110                .map_err(BuildError::InvalidAsset)?;
111        }
112        for (primitive_index, primitive) in self.asset.primitives().iter().enumerate() {
113            let Some(skin_index) = primitive.skin_index() else {
114                continue;
115            };
116            let Some(skin) = self.asset.skins.get(skin_index) else {
117                // The common asset validator reports the missing skin reference.
118                continue;
119            };
120            let joint_count = skin.joints().len();
121            let has_invalid_joint = primitive.skinning_sets().iter().any(|set| {
122                set.joints()
123                    .iter()
124                    .zip(set.weights())
125                    .any(|(joints, weights)| {
126                        joints
127                            .iter()
128                            .zip(weights)
129                            .any(|(&joint, &weight)| weight > 0.0 && joint as usize >= joint_count)
130                    })
131            });
132            if has_invalid_joint {
133                return Err(BuildError::InvalidAsset(format!(
134                    "primitive {primitive_index} has a weighted joint outside skin {skin_index}"
135                )));
136            }
137        }
138        self.asset.validate_programmatic()?;
139        Ok(self.asset)
140    }
141}
142
143impl Default for AvatarAssetBuilder {
144    fn default() -> Self {
145        Self::new()
146    }
147}