use crate::node::AvatarNode;
use crate::{
Avatar, AvatarAsset, AvatarImage, AvatarMeta, AvatarTexture, BuildError, Expressions,
FirstPerson, Humanoid, LookAt, Material, NodeConstraint, RenderPrimitive, Skin, SpringBone,
};
#[derive(Debug)]
pub struct AvatarAssetBuilder {
asset: Avatar,
}
impl AvatarAssetBuilder {
pub fn new() -> Self {
Self {
asset: Avatar::new(),
}
}
pub fn with_meta(mut self, meta: AvatarMeta) -> Self {
self.asset = self.asset.with_meta(meta);
self
}
pub fn with_humanoid(mut self, humanoid: Humanoid) -> Self {
self.asset = self.asset.with_humanoid(humanoid);
self
}
pub fn with_expressions(mut self, expressions: Expressions) -> Self {
self.asset = self.asset.with_expressions(expressions);
self
}
pub fn with_nodes(mut self, nodes: Vec<AvatarNode>) -> Self {
self.asset = self.asset.with_nodes(nodes);
self
}
pub fn with_primitives(mut self, primitives: Vec<RenderPrimitive>) -> Self {
self.asset = self.asset.with_primitives(primitives);
self
}
pub fn with_images(mut self, images: Vec<AvatarImage>) -> Self {
self.asset.images = images;
self
}
pub fn with_materials(mut self, materials: Vec<Material>) -> Self {
self.asset.materials = materials;
self
}
pub fn with_textures(mut self, textures: Vec<AvatarTexture>) -> Self {
self.asset.textures = textures;
self
}
pub fn with_skins(mut self, skins: Vec<Skin>) -> Self {
self.asset.skins = skins;
self
}
pub fn with_look_at(mut self, look_at: LookAt) -> Self {
self.asset = self.asset.with_look_at(look_at);
self
}
pub fn with_first_person(mut self, first_person: FirstPerson) -> Self {
self.asset.first_person = first_person;
self
}
pub fn with_constraints(mut self, constraints: Vec<NodeConstraint>) -> Self {
self.asset = self.asset.with_node_constraints(constraints);
self
}
pub fn with_spring_bone(mut self, spring_bone: SpringBone) -> Self {
self.asset = self.asset.with_spring_bone(spring_bone);
self
}
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 {
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()
}
}