1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
//! Port of `three.js/src/objects/SkinnedMesh.js`.
use std::cell::RefCell;
use std::rc::Rc;
use crate::core::{BufferGeometry, Object3D, ObjectRef};
use crate::materials::MeshBasicNodeMaterial;
use crate::math::{Box3, Matrix4, Sphere, Vector3, Vector4};
use crate::objects::{Mesh, Payload, Skeleton};
/// `AttachedBindMode` / `DetachedBindMode` from `src/constants.js`.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum BindMode {
/// `'attached'` — the bind matrix inverse tracks `matrixWorld`.
#[default]
Attached,
/// `'detached'` — it tracks `bindMatrix`.
Detached,
}
/// `class SkinnedMesh extends Mesh`.
///
/// The `Mesh` half is held rather than inherited, exactly as
/// [`InstancedMesh`](crate::objects::InstancedMesh) holds it, and the whole
/// struct is one node's [`Payload`] — so the renderer's tree walk finds a
/// skinned mesh wherever it hangs, and the bones (which are ordinary nodes in
/// the same tree) reach it through their shared [`Skeleton`].
#[derive(Clone)]
pub struct SkinnedMesh {
/// The `Mesh` it extends: `geometry` and `material`.
pub mesh: Mesh,
/// `SkinnedMesh.skeleton`.
pub skeleton: Option<Rc<RefCell<Skeleton>>>,
/// `SkinnedMesh.bindMode`.
pub bind_mode: BindMode,
/// `SkinnedMesh.bindMatrix`.
pub bind_matrix: Matrix4,
/// `SkinnedMesh.bindMatrixInverse`.
///
/// In the default [`BindMode::Attached`] this is `matrixWorld⁻¹`, recomputed
/// **every frame** by `Object3D.updateMatrixWorld()` — see
/// `SkinnedMesh::update_bind_matrix_inverse`, which the tree walk calls
/// for this payload the way three.js' `SkinnedMesh.updateMatrixWorld()`
/// override does. A stale or identity value here scales the skin by the
/// node's own scale and is silent.
pub bind_matrix_inverse: Matrix4,
/// `Mesh.boundingBox` (`SkinnedMesh.computeBoundingBox`).
pub bounding_box: Option<Box3>,
/// `Mesh.boundingSphere` (`SkinnedMesh.computeBoundingSphere`).
pub bounding_sphere: Option<Sphere>,
/// `Mesh.morphTargetInfluences`, which glTF morph animation writes into.
/// Shared, because `SceneResolver` binds a `.morphTargetInfluences` track to
/// it while the mesh is owned elsewhere.
pub morph_target_influences: Rc<RefCell<Vec<f64>>>,
/// `Mesh.morphTargetDictionary`.
pub morph_target_dictionary: Vec<(String, usize)>,
}
impl SkinnedMesh {
/// `new SkinnedMesh( geometry, material )`, as a scene-graph [`ObjectRef`].
#[allow(clippy::new_ret_no_self)] // `new` mirrors three.js's constructor and returns a scene-graph `ObjectRef`, not `Self`; public API, not changing.
pub fn new(
geometry: Rc<BufferGeometry>,
material: impl Into<Option<MeshBasicNodeMaterial>>,
) -> ObjectRef {
let mut object = Object3D {
object_type: "SkinnedMesh",
..Default::default()
};
object.payload = Payload::SkinnedMesh(Box::new(Self::of(geometry, material.into())));
object.into_node()
}
/// The payload on its own, for a caller that already has the node —
/// `GLTFLoader`, which builds the node from the glTF node definition first.
pub fn of(geometry: Rc<BufferGeometry>, material: Option<MeshBasicNodeMaterial>) -> Self {
Self {
mesh: Mesh {
geometry,
material,
materials: Vec::new(),
morph_target_influences: Vec::new(),
line_segments: None,
count: None,
},
skeleton: None,
bind_mode: BindMode::Attached,
bind_matrix: Matrix4::identity(),
bind_matrix_inverse: Matrix4::identity(),
bounding_box: None,
bounding_sphere: None,
morph_target_influences: Rc::new(RefCell::new(Vec::new())),
morph_target_dictionary: Vec::new(),
}
}
/// `SkinnedMesh.geometry`.
pub fn geometry(&self) -> &Rc<BufferGeometry> {
&self.mesh.geometry
}
/// `SkinnedMesh.bind( skeleton, bindMatrix )` for a mesh that is already a
/// node — the node is needed for three.js' `bindMatrix === undefined`
/// branch, which updates the world matrix and takes it.
pub fn bind(node: &ObjectRef, skeleton: Rc<RefCell<Skeleton>>, bind_matrix: Option<Matrix4>) {
let bind_matrix = match bind_matrix {
Some(matrix) => matrix,
None => {
node.update_matrix_world(true);
skeleton.borrow_mut().calculate_inverses();
node.borrow().matrix_world
}
};
let mut object = node.borrow_mut();
let skin = object
.payload
.skinned_mesh_mut()
.expect("three-rs: SkinnedMesh::bind needs a SkinnedMesh node");
skin.skeleton = Some(skeleton);
skin.bind_matrix.copy(&bind_matrix);
skin.bind_matrix_inverse.copy(&bind_matrix);
skin.bind_matrix_inverse.invert();
}
/// The tail of `SkinnedMesh.updateMatrixWorld( force )`: everything after
/// `super.updateMatrixWorld( force )`. The tree walk
/// (`Object3D.updateMatrixWorld`) runs it for every `SkinnedMesh` payload it
/// passes, which is what keeps `bindMatrixInverse` in step with a moving or
/// scaled parent without the caller having to remember.
pub(crate) fn update_bind_matrix_inverse(&mut self, matrix_world: &Matrix4) {
match self.bind_mode {
BindMode::Attached => {
self.bind_matrix_inverse.copy(matrix_world);
self.bind_matrix_inverse.invert();
}
BindMode::Detached => {
self.bind_matrix_inverse.copy(&self.bind_matrix);
self.bind_matrix_inverse.invert();
}
}
}
/// `SkinnedMesh.pose()`.
pub fn pose(&mut self) {
if let Some(skeleton) = &self.skeleton {
skeleton.borrow_mut().pose();
}
}
/// `SkinnedMesh.normalizeSkinWeights()`. Mutates the geometry, so it takes
/// the geometry out of the `Rc` (three.js mutates in place; an `Rc` shared
/// with the renderer cannot be).
pub fn normalize_skin_weights(&mut self) {
let mut geometry = (*self.mesh.geometry).clone();
let Some(skin_weight) = geometry.get_attribute_mut("skinWeight") else {
return;
};
let mut vector = Vector4::default();
for i in 0..skin_weight.count() {
vector.set(
skin_weight.get_x(i),
skin_weight.get_y(i),
skin_weight.get_z(i),
skin_weight.get_w(i),
);
let scale = 1.0 / vector.manhattan_length();
if scale.is_finite() {
vector.multiply_scalar(scale);
} else {
// fix gltf files with all zero weights
vector.set(1.0, 0.0, 0.0, 0.0);
}
skin_weight.set_x(i, vector.x);
skin_weight.set_y(i, vector.y);
skin_weight.set_z(i, vector.z);
skin_weight.set_w(i, vector.w);
}
self.mesh.geometry = Rc::new(geometry);
}
/// `SkinnedMesh.applyBoneTransform( index, vector )`.
pub fn apply_bone_transform(&self, index: usize, vector: &mut Vector3) {
let Some(skeleton) = &self.skeleton else {
return;
};
let skeleton = skeleton.borrow();
let (Some(skin_index), Some(skin_weight)) = (
self.mesh.geometry.get_attribute("skinIndex"),
self.mesh.geometry.get_attribute("skinWeight"),
) else {
return;
};
let mut base_position = *vector;
base_position.apply_matrix4(&self.bind_matrix);
vector.set(0.0, 0.0, 0.0);
for i in 0..4 {
let weight = match i {
0 => skin_weight.get_x(index),
1 => skin_weight.get_y(index),
2 => skin_weight.get_z(index),
_ => skin_weight.get_w(index),
};
if weight == 0.0 {
continue;
}
let bone_index = match i {
0 => skin_index.get_x(index),
1 => skin_index.get_y(index),
2 => skin_index.get_z(index),
_ => skin_index.get_w(index),
} as usize;
let mut offset_matrix = Matrix4::identity();
offset_matrix.multiply_matrices(
&skeleton.bones[bone_index].borrow().matrix_world,
&skeleton.bone_inverses[bone_index],
);
let mut temp = base_position;
temp.apply_matrix4(&offset_matrix);
vector.add_scaled_vector(&temp, weight);
}
vector.apply_matrix4(&self.bind_matrix_inverse);
}
/// `SkinnedMesh.computeBoundingBox()`.
pub fn compute_bounding_box(&mut self) {
let Some(position) = self.mesh.geometry.position() else {
return;
};
let count = position.count();
let mut bounding_box = Box3::default();
bounding_box.make_empty();
for i in 0..count {
let mut vertex = Vector3::new(position.get_x(i), position.get_y(i), position.get_z(i));
self.apply_bone_transform(i, &mut vertex);
bounding_box.expand_by_point(&vertex);
}
self.bounding_box = Some(bounding_box);
}
/// `SkinnedMesh.computeBoundingSphere()`.
pub fn compute_bounding_sphere(&mut self) {
let Some(position) = self.mesh.geometry.position() else {
return;
};
let count = position.count();
let mut bounding_sphere = Sphere::default();
bounding_sphere.make_empty();
for i in 0..count {
let mut vertex = Vector3::new(position.get_x(i), position.get_y(i), position.get_z(i));
self.apply_bone_transform(i, &mut vertex);
bounding_sphere.expand_by_point(&vertex);
}
self.bounding_sphere = Some(bounding_sphere);
}
/// `SkinnedMesh.getVertexPosition( index, target )` — `Mesh`'s morphed
/// position, then `applyBoneTransform()`.
pub fn get_vertex_position(&self, index: usize) -> Vector3 {
let mut target = crate::objects::mesh::vertex_position(
&self.mesh.geometry,
&self.morph_target_influences.borrow(),
index,
);
self.apply_bone_transform(index, &mut target);
target
}
/// `SkinnedMesh.raycast( raycaster, intersects )` — `Mesh.raycast()` over
/// the skinned mesh's *own* bounds, which follow the bones, with a plain
/// `ray.intersectsSphere()` test where `Mesh` checks `near` / `far`.
///
/// A missing material is three's default `MeshBasicMaterial`, as for
/// [`Mesh::raycast`](crate::objects::Mesh::raycast).
pub fn raycast(
&mut self,
matrix_world: &Matrix4,
object: &crate::core::ObjectRef,
raycaster: &crate::core::Raycaster,
intersects: &mut Vec<crate::core::Intersection>,
) {
// Test with the bounding sphere in world space.
if self.bounding_sphere.is_none() {
self.compute_bounding_sphere();
}
let Some(mut sphere) = self.bounding_sphere else {
return;
};
sphere.apply_matrix4(matrix_world);
if !raycaster.ray.intersects_sphere(&sphere) {
return;
}
// Convert the ray to the local space of the skinned mesh.
let mut inverse_matrix = *matrix_world;
inverse_matrix.invert();
let mut ray = raycaster.ray;
ray.apply_matrix4(&inverse_matrix);
// Test with the bounding box in local space.
if let Some(bounding_box) = &self.bounding_box {
if !ray.intersects_box(bounding_box) {
return;
}
}
let this = &*self;
let target = crate::objects::mesh::MeshRaycast {
geometry: &this.mesh.geometry,
side: this
.mesh
.material
.as_ref()
.map_or(crate::materials::Side::Front, |m| m.side),
matrix_world: *matrix_world,
draw_start: this.mesh.geometry.draw_range.start,
draw_count: this.mesh.geometry.draw_range.count,
vertex_position: &|index| this.get_vertex_position(index),
};
target.compute_intersections(raycaster, &ray, object, intersects);
}
}