use std::rc::Rc;
use crate::nodes::node::{
BufferId, BufferNode, BufferSource, Node, Type, UniformGroup, UniformSource,
};
use crate::nodes::tsl::*;
use crate::nodes::NodeRef;
#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq)]
pub struct SkinEntry {
pub bones: usize,
}
fn bone_matrices(entry: &SkinEntry) -> Rc<BufferNode> {
Rc::new(BufferNode {
id: BufferId::next(),
source: BufferSource::BoneMatrices,
element_ty: Type::Mat4,
count: entry.bones.max(1),
})
}
fn bone(buffer: &Rc<BufferNode>, index: NodeRef) -> NodeRef {
NodeRef::new(Node::BufferElement {
buffer: buffer.clone(),
index,
})
}
pub fn skinning(entry: &SkinEntry) -> Vec<NodeRef> {
let skin_index = attribute("skinIndex", Type::UVec4);
let skin_weight = attribute("skinWeight", Type::Vec4);
let bind_matrix = uniform(
UniformSource::BindMatrix,
Type::Mat4,
UniformGroup::Object,
None,
);
let bind_matrix_inverse = uniform(
UniformSource::BindMatrixInverse,
Type::Mat4,
UniformGroup::Object,
None,
);
let buffer = bone_matrices(entry);
let mats = [
bone(&buffer, skin_index.x()),
bone(&buffer, skin_index.y()),
bone(&buffer, skin_index.z()),
bone(&buffer, skin_index.w()),
];
let weights = [
skin_weight.x(),
skin_weight.y(),
skin_weight.z(),
skin_weight.w(),
];
let mut statements = Vec::new();
let skin_vertex = to_var(
None,
bind_matrix.mul(vec4_join(vec![position_local(), float(1.0)])),
);
let skinned = (0..4)
.map(|i| mats[i].mul(weights[i].clone()).mul(skin_vertex.clone()))
.reduce(|a, b| a.add(b))
.expect("three-rs: four bone terms");
statements.push(position_local().assign(bind_matrix_inverse.mul(skinned).xyz()));
let skin_matrix = (0..4)
.map(|i| weights[i].mul(mats[i].clone()))
.reduce(|a, b| a.add(b))
.expect("three-rs: four bone terms");
let skin_matrix = bind_matrix_inverse.mul(skin_matrix).mul(bind_matrix);
let skin_matrix3 = join(
Type::Mat3,
vec![
skin_matrix.element(0).xyz(),
skin_matrix.element(1).xyz(),
skin_matrix.element(2).xyz(),
],
);
statements.push(normal_local().assign(skin_matrix3.mul(normal_local())));
statements
}
pub fn compute_skinning(mesh: &crate::core::Node) -> NodeRef {
use crate::nodes::node::{LiveValue, SkeletonRef};
use crate::objects::Payload;
let (geometry, skeleton) = match &mesh.borrow().payload {
Payload::SkinnedMesh(skinned) => (
skinned.mesh.geometry.clone(),
skinned
.skeleton
.clone()
.expect("three-rs: computeSkinning() on a SkinnedMesh with no skeleton"),
),
_ => panic!("three-rs: computeSkinning() needs a SkinnedMesh"),
};
let attribute = |name: &str| {
geometry
.get_attribute(name)
.unwrap_or_else(|| panic!("three-rs: computeSkinning() needs `{name}`"))
};
let position = storage_f32(&attribute("position").array(), Type::Vec3).to_read_only();
let indices: Vec<u32> = attribute("skinIndex")
.array()
.iter()
.map(|&v| v as u32)
.collect();
let skin_index = storage_data(&indices, Type::UVec4).to_read_only();
let skin_weight = storage_f32(&attribute("skinWeight").array(), Type::Vec4).to_read_only();
let skinned = |read: fn(&crate::objects::SkinnedMesh) -> Vec<f64>| {
let mesh = mesh.downgrade();
uniform(
UniformSource::Live(LiveValue::new(move || {
let mesh = mesh
.upgrade()
.expect("three-rs: computeSkinning() outlived its mesh");
let node = mesh.borrow();
match &node.payload {
Payload::SkinnedMesh(skinned) => read(skinned),
_ => unreachable!("three-rs: checked above"),
}
})),
Type::Mat4,
UniformGroup::Object,
None,
)
};
let bind_matrix = skinned(|m| m.bind_matrix.elements.to_vec());
let bind_matrix_inverse = skinned(|m| m.bind_matrix_inverse.elements.to_vec());
let bones = skeleton.borrow().bones.len();
let buffer = Rc::new(BufferNode {
id: BufferId::next(),
source: BufferSource::SkeletonBoneMatrices(SkeletonRef(skeleton)),
element_ty: Type::Mat4,
count: bones.max(1),
});
let index = to_var(None, skin_index.element(instance_index()));
let weight = to_var(None, skin_weight.element(instance_index()));
let position = to_var(None, position.element(instance_index()));
let mats = [
bone(&buffer, index.x()),
bone(&buffer, index.y()),
bone(&buffer, index.z()),
bone(&buffer, index.w()),
];
let weights = [weight.x(), weight.y(), weight.z(), weight.w()];
let skin_vertex = bind_matrix.mul(vec4_join(vec![position, float(1.0)]));
let skinned = (0..4)
.map(|i| weights[i].mul(mats[i].clone()).mul(skin_vertex.clone()))
.reduce(|a, b| a.add(b))
.expect("three-rs: four bone terms");
bind_matrix_inverse.mul(skinned).xyz()
}