1use crate::{Mat4, Mesh, Vec3, retained::ResidentMesh};
4use ferravex_graphics::Bounds;
5pub const MAX_SKIN_JOINTS: usize = 32;
8pub const MAX_FRAME_SKIN_JOINTS: usize = 32768;
9pub const MAX_SKIN_VERTICES: usize = 65536;
10#[derive(Clone, Copy, Debug)]
11pub struct SkinWeights {
12 pub joints: [u16; 4],
13 pub weights: [f32; 4],
14}
15impl SkinWeights {
16 pub fn rigid(joint: u16) -> Self {
17 Self {
18 joints: [joint; 4],
19 weights: [1., 0., 0., 0.],
20 }
21 }
22 fn packed(self, count: usize) -> Result<[f32; 8], &'static str> {
23 if self.joints.iter().any(|i| *i as usize >= count)
24 || self.weights.iter().any(|v| !v.is_finite() || *v < 0.)
25 {
26 return Err("invalid skin weights/joints");
27 }
28 let sum = self.weights.iter().map(|v| f64::from(*v)).sum::<f64>();
29 if sum <= 0. {
30 return Err("skin weights sum to zero");
31 }
32 Ok(std::array::from_fn(|i| {
33 if i < 4 {
34 self.joints[i] as f32
35 } else {
36 (f64::from(self.weights[i - 4]) / sum) as f32
37 }
38 }))
39 }
40}
41#[derive(Clone)]
42pub struct SkinnedMesh {
43 mesh: ResidentMesh,
44 joints: usize,
45 bounds: [Option<Bounds>; MAX_SKIN_JOINTS],
46}
47impl SkinnedMesh {
48 pub fn new(mesh: &Mesh, weights: &[SkinWeights], joints: usize) -> Result<Self, &'static str> {
51 if joints == 0
52 || joints > MAX_SKIN_JOINTS
53 || weights.len() != mesh.vertices.len()
54 || mesh.vertices.len() > MAX_SKIN_VERTICES
55 {
56 return Err("invalid skin joint/vertex count");
57 }
58 let packed: Vec<_> = weights
59 .iter()
60 .map(|w| w.packed(joints))
61 .collect::<Result<_, _>>()?;
62 let mut bounds: [Option<Bounds>; MAX_SKIN_JOINTS] = [None; MAX_SKIN_JOINTS];
63 for index in &mesh.indices {
64 let i = *index as usize;
65 let p = mesh
66 .vertices
67 .get(i)
68 .ok_or("skin index out of bounds")?
69 .position;
70 for j in 0..4 {
71 if packed[i][4 + j] > 0. {
72 let at = packed[i][j] as usize;
73 bounds[at] = Some(bounds[at].map_or(Bounds { min: p, max: p }, |b| Bounds {
74 min: b.min.min(p),
75 max: b.max.max(p),
76 }));
77 }
78 }
79 }
80 let resident = ResidentMesh::with_skin(mesh, Some((&packed, joints)))?;
81 Ok(Self {
82 mesh: resident,
83 joints,
84 bounds,
85 })
86 }
87 pub fn resident(&self) -> &ResidentMesh {
88 &self.mesh
89 }
90 pub fn joint_count(&self) -> usize {
91 self.joints
92 }
93 pub fn bounds(&self, palette: &SkinPalette) -> Result<Bounds, &'static str> {
96 if self.joints != palette.count {
97 return Err("skin palette joint count mismatch");
98 }
99 let mut bound = Bounds {
100 min: Vec3::splat(f32::INFINITY),
101 max: Vec3::splat(f32::NEG_INFINITY),
102 };
103 for (i, b) in self.bounds.iter().enumerate().take(self.joints) {
104 if let Some(b) = b {
105 let m = Mat4::from_cols_array(&palette.matrices[i]);
106 for x in [b.min.x, b.max.x] {
107 for y in [b.min.y, b.max.y] {
108 for z in [b.min.z, b.max.z] {
109 let p = m.transform_point3(Vec3::new(x, y, z));
110 if !p.is_finite() {
111 return Err("skin bounds overflow");
112 }
113 bound.min = bound.min.min(p);
114 bound.max = bound.max.max(p);
115 }
116 }
117 }
118 }
119 }
120 let padding = bound.min.abs().max(bound.max.abs()).max_element() * 0.00001 + 0.00001;
122 bound.min -= Vec3::splat(padding);
123 bound.max += Vec3::splat(padding);
124 if !bound.min.is_finite() || !bound.max.is_finite() {
125 return Err("skin bounds overflow");
126 }
127 Ok(bound)
128 }
129}
130#[derive(Clone)]
134pub struct SkinPalette {
135 pub(crate) count: usize,
136 pub(crate) matrices: [[f32; 16]; MAX_SKIN_JOINTS],
137 pub(crate) normals: [[f32; 9]; MAX_SKIN_JOINTS],
138}
139impl SkinPalette {
140 pub fn new(matrices: &[[f32; 16]]) -> Result<Self, &'static str> {
141 let mut result = Self {
142 count: 0,
143 matrices: [[0.; 16]; MAX_SKIN_JOINTS],
144 normals: [[0.; 9]; MAX_SKIN_JOINTS],
145 };
146 result.set(matrices)?;
147 Ok(result)
148 }
149 pub fn set(&mut self, matrices: &[[f32; 16]]) -> Result<(), &'static str> {
150 if matrices.is_empty() || matrices.len() > MAX_SKIN_JOINTS {
151 return Err("invalid skin palette length");
152 }
153 let mut normals = [[0.; 9]; MAX_SKIN_JOINTS];
154 for (i, columns) in matrices.iter().enumerate() {
155 let m = Mat4::from_cols_array(columns);
156 if !m.is_finite()
157 || columns[3] != 0.
158 || columns[7] != 0.
159 || columns[11] != 0.
160 || columns[15] != 1.
161 {
162 return Err("invalid skin transform");
163 }
164 let n = m
165 .try_inverse()
166 .ok_or("singular skin transform")?
167 .transpose()
168 .to_cols_array();
169 normals[i] = [n[0], n[1], n[2], n[4], n[5], n[6], n[8], n[9], n[10]];
170 }
171 self.count = matrices.len();
172 self.matrices[..self.count].copy_from_slice(matrices);
173 self.normals = normals;
174 Ok(())
175 }
176 pub fn joint_count(&self) -> usize {
177 self.count
178 }
179 pub fn matrices(&self) -> &[[f32; 16]] {
180 &self.matrices[..self.count]
181 }
182 pub fn transform_point(&self, point: Vec3, weights: SkinWeights) -> Result<Vec3, &'static str> {
184 if !point.is_finite() {
185 return Err("invalid skin point");
186 }
187 let weights = weights.packed(self.count)?;
188 let mut out = Vec3::ZERO;
189 for i in 0..4 {
190 out += Mat4::from_cols_array(&self.matrices[weights[i] as usize])
191 .transform_point3(point)
192 * weights[4 + i];
193 }
194 if out.is_finite() {
195 Ok(out)
196 } else {
197 Err("skin point overflow")
198 }
199 }
200}
201
202#[cfg(test)]
203mod tests {
204 use super::*;
205 use crate::{
206 GREEN, Vec2,
207 mesh::Mesh3d,
208 retained::{DrawStyle, Frame},
209 };
210 #[test]
211 fn visibility_uses_deformed_bounds_instead_of_bind_bounds() {
212 let mut mesh = Mesh3d::cuboid(Vec3::ONE, GREEN).mesh;
213 for v in &mut mesh.vertices {
214 v.position.x += 100.;
215 }
216 let skin =
217 SkinnedMesh::new(&mesh, &vec![SkinWeights::rigid(0); mesh.vertices.len()], 1).unwrap();
218 let mut palette =
219 SkinPalette::new(&[Mat4::from_translation(-Vec3::X * 100.).to_cols_array()]).unwrap();
220 crate::set_camera(&crate::Camera3D {
221 position: Vec3::new(0., 1., 8.),
222 target: Vec3::ZERO,
223 ..Default::default()
224 });
225 assert!(crate::draw_skinned(&skin, Mat4::IDENTITY, &palette));
226 palette.set(&[Mat4::IDENTITY.to_cols_array()]).unwrap();
227 assert!(!crate::draw_skinned(&skin, Mat4::IDENTITY, &palette));
228 crate::set_default_camera();
229 }
230 #[test]
231 fn weights_are_validated_and_normalized_once() {
232 let mesh = Mesh3d::plane(Vec2::ONE, GREEN, 1).mesh;
233 let weights = vec![
234 SkinWeights {
235 joints: [0, 1, 0, 1],
236 weights: [2., 2., 0., 0.]
237 };
238 mesh.vertices.len()
239 ];
240 let skin = SkinnedMesh::new(&mesh, &weights, 2).unwrap();
241 let palette = SkinPalette::new(&[
242 Mat4::IDENTITY.to_cols_array(),
243 Mat4::from_translation(Vec3::X * 2.).to_cols_array(),
244 ])
245 .unwrap();
246 let point = palette.transform_point(Vec3::ZERO, weights[0]).unwrap();
247 assert_eq!(point, Vec3::X);
248 let packed = crate::retained::geometry(skin.resident().id()).unwrap();
249 assert_eq!(
250 packed.skin.as_ref().unwrap()[0],
251 [0., 1., 0., 1., 0.5, 0.5, 0., 0.]
252 );
253 for invalid in [
254 SkinWeights {
255 joints: [0; 4],
256 weights: [0.; 4],
257 },
258 SkinWeights {
259 joints: [0; 4],
260 weights: [f32::NAN, 0., 0., 0.],
261 },
262 SkinWeights {
263 joints: [0; 4],
264 weights: [-1., 2., 0., 0.],
265 },
266 SkinWeights {
267 joints: [3; 4],
268 weights: [1., 0., 0., 0.],
269 },
270 ] {
271 assert!(SkinnedMesh::new(&mesh, &vec![invalid; mesh.vertices.len()], 2).is_err());
272 }
273 assert!(SkinnedMesh::new(&mesh, &weights, 33).is_err());
274 assert!(SkinnedMesh::new(&mesh, &weights[..1], 2).is_err());
275 let huge = SkinWeights {
276 joints: [0; 4],
277 weights: [f32::MAX; 4],
278 };
279 assert_eq!(huge.packed(1).unwrap()[4..], [0.25; 4]);
280 }
281 #[test]
282 fn palette_validation_is_transactional_and_normals_use_inverse_transpose() {
283 let scale = Mat4::from_scale(Vec3::new(2., 4., 8.)).to_cols_array();
284 let mut palette = SkinPalette::new(&[scale]).unwrap();
285 assert_eq!(
286 palette.normals[0],
287 [0.5, 0., 0., 0., 0.25, 0., 0., 0., 0.125]
288 );
289 for bad in [
290 Mat4::from_scale(Vec3::ZERO).to_cols_array(),
291 Mat4::perspective_rh_gl(1., 1., 0.1, 10.).to_cols_array(),
292 [f32::NAN; 16],
293 ] {
294 assert!(palette.set(&[bad]).is_err());
295 assert_eq!(palette.matrices(), &[scale]);
296 }
297 assert!(palette.set(&[]).is_err());
298 assert_eq!(palette.joint_count(), 1);
299 }
300 #[test]
301 fn animated_bounds_enclose_weighted_vertices_and_draws_snapshot_palettes() {
302 let mesh = Mesh3d::cuboid(Vec3::ONE, GREEN).mesh;
303 let weights = vec![
304 SkinWeights {
305 joints: [0, 1, 0, 1],
306 weights: [0.25, 0.75, 0., 0.]
307 };
308 mesh.vertices.len()
309 ];
310 let skin = SkinnedMesh::new(&mesh, &weights, 2).unwrap();
311 let mut palette = SkinPalette::new(&[
312 Mat4::from_translation(Vec3::X * 3.).to_cols_array(),
313 (Mat4::from_translation(Vec3::Y * 2.) * Mat4::from_scale(Vec3::new(2., 1., 3.)))
314 .to_cols_array(),
315 ])
316 .unwrap();
317 let bounds = skin.bounds(&palette).unwrap();
318 for v in &mesh.vertices {
319 let p = palette.transform_point(v.position, weights[0]).unwrap();
320 assert!(
321 p.x >= bounds.min.x
322 && p.x <= bounds.max.x
323 && p.y >= bounds.min.y
324 && p.y <= bounds.max.y
325 && p.z >= bounds.min.z
326 && p.z <= bounds.max.z
327 );
328 }
329 let mut frame = Frame::default();
330 for _ in 0..2 {
331 assert!(frame.record_style(
332 skin.resident(),
333 Mat4::IDENTITY,
334 Mat4::IDENTITY,
335 true,
336 DrawStyle {
337 skin: Some(&palette),
338 ..Default::default()
339 }
340 ));
341 }
342 assert_eq!(frame.batches.len(), 1);
343 assert_eq!(frame.batches[0].count, 2);
344 assert_eq!(frame.skin_matrices.len(), 2);
345 let previous = frame.skin_matrices.clone();
346 palette.set(&[Mat4::IDENTITY.to_cols_array(); 2]).unwrap();
347 assert_eq!(frame.skin_matrices, previous);
348 assert!(frame.record_style(
349 skin.resident(),
350 Mat4::IDENTITY,
351 Mat4::IDENTITY,
352 true,
353 DrawStyle {
354 skin: Some(&palette),
355 ..Default::default()
356 }
357 ));
358 frame.finalize();
359 assert_eq!(frame.batches.len(), 2);
360 assert_eq!(frame.batches[0].reserved, [0, 2]);
361 assert_eq!(frame.batches[1].reserved, [2, 2]);
362 assert!(!frame.record(skin.resident(), Mat4::IDENTITY, Mat4::IDENTITY, true, None));
363 assert!(
364 skin.bounds(&SkinPalette::new(&[Mat4::IDENTITY.to_cols_array()]).unwrap())
365 .is_err()
366 );
367 frame.clear();
368 assert!(frame.skin_matrices.is_empty());
369 assert!(frame.skin_normals.is_empty());
370 }
371}