1use glam::{Mat4, Vec3};
32
33use super::{Geometry, InstanceDesc, SceneDesc};
34use crate::cull::Aabb;
35use crate::mesh_pool::vertex_positions;
36use crcbl_shaders::mesh::VERTEX_STRIDE;
37
38#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
42pub enum SceneBoundsError {
43 #[error("instance {instance} names mesh {mesh}, which the scene does not have")]
45 MissingMesh {
46 instance: usize,
48 mesh: usize,
50 },
51 #[error("instance {instance} names mesh {mesh}, a cluster DAG with no levels")]
54 NoLevels {
55 instance: usize,
57 mesh: usize,
59 },
60 #[error("instance {instance} names mesh {mesh}, whose vertex bytes end in a partial vertex")]
62 PartialVertex {
63 instance: usize,
65 mesh: usize,
67 },
68 #[error("instance {instance}'s vertex {vertex} is not finite once placed")]
71 NonFinitePosition {
72 instance: usize,
74 vertex: usize,
76 },
77 #[error("instance {instance}'s mesh has no vertices")]
79 EmptyPart {
80 instance: usize,
82 },
83 #[error("the instances have no vertices to bound")]
86 Empty,
87}
88
89impl SceneDesc<'_> {
90 pub fn instance_bounds(
109 &self,
110 instances: &[InstanceDesc],
111 root: Mat4,
112 ) -> Result<Aabb, SceneBoundsError> {
113 let mut bounds: Option<Aabb> = None;
114 for (index, instance) in instances.iter().enumerate() {
115 if let Some(placed) = self.placed_bounds(index, instance, root)? {
116 bounds = Some(match bounds {
117 Some(so_far) => Aabb {
118 min: so_far.min.min(placed.min),
119 max: so_far.max.max(placed.max),
120 },
121 None => placed,
122 });
123 }
124 }
125 bounds.ok_or(SceneBoundsError::Empty)
126 }
127
128 pub fn instance_parts(
143 &self,
144 instances: &[InstanceDesc],
145 ) -> Result<Vec<Aabb>, SceneBoundsError> {
146 instances
147 .iter()
148 .enumerate()
149 .map(|(index, instance)| {
150 self.placed_bounds(index, instance, Mat4::IDENTITY)?
151 .ok_or(SceneBoundsError::EmptyPart { instance: index })
152 })
153 .collect()
154 }
155
156 fn placed_bounds(
160 &self,
161 index: usize,
162 instance: &InstanceDesc,
163 root: Mat4,
164 ) -> Result<Option<Aabb>, SceneBoundsError> {
165 let mesh = instance.mesh;
166 let geometry = &self
167 .meshes
168 .get(mesh)
169 .ok_or(SceneBoundsError::MissingMesh {
170 instance: index,
171 mesh,
172 })?
173 .geometry;
174 let vertices = match geometry {
175 Geometry::Flat { vertices, .. } => vertices.as_ref(),
176 Geometry::Dag { levels, .. } => levels
177 .first()
178 .ok_or(SceneBoundsError::NoLevels {
179 instance: index,
180 mesh,
181 })?
182 .as_ref(),
183 };
184 if vertices.len() % VERTEX_STRIDE != 0 {
185 return Err(SceneBoundsError::PartialVertex {
186 instance: index,
187 mesh,
188 });
189 }
190 let transform = root * instance.transform;
191 let mut bounds: Option<Aabb> = None;
192 for (vertex, position) in vertex_positions(vertices).enumerate() {
193 let point: Vec3 = transform.transform_point3(position);
194 if !point.is_finite() {
195 return Err(SceneBoundsError::NonFinitePosition {
196 instance: index,
197 vertex,
198 });
199 }
200 bounds = Some(match bounds {
203 Some(so_far) => Aabb {
204 min: so_far.min.min(point),
205 max: so_far.max.max(point),
206 },
207 None => Aabb {
208 min: point,
209 max: point,
210 },
211 });
212 }
213 Ok(bounds)
214 }
215}
216
217#[cfg(test)]
218mod tests {
219 use std::borrow::Cow;
220 use std::f32::consts::{FRAC_1_SQRT_2, FRAC_PI_2, FRAC_PI_4};
221
222 use crcbl_phys::{AabbCompound, Ray, Transform};
223 use crcbl_shaders::mesh::{self, MeshVertex};
224 use crcbl_shaders::meshlet::MeshClusters;
225 use crcbl_shaders::vertex::UvRange;
226 use glam::{DQuat, DVec3};
227
228 use super::*;
229 use crate::scene::{DEMO_CUBE, MeshDesc, demo};
230
231 fn cube(transform: Mat4) -> InstanceDesc {
232 InstanceDesc {
233 mesh: DEMO_CUBE,
234 material: 0,
235 transform,
236 }
237 }
238
239 fn with_mesh(positions: &[[f32; 3]]) -> (SceneDesc<'static>, usize) {
242 let vertices: Vec<MeshVertex> = positions
243 .iter()
244 .map(|&position| {
245 MeshVertex::from_normal(
246 position,
247 [0.0, 1.0, 0.0],
248 [1.0; 4],
249 [0.0; 2],
250 &UvRange::default(),
251 )
252 })
253 .collect();
254 let mut scene = demo();
255 scene.meshes.push(MeshDesc {
256 label: Cow::Borrowed("test mesh"),
257 geometry: Geometry::Flat {
258 vertices: Cow::Owned(mesh::vertex_bytes(&vertices)),
259 uv_range: UvRange::default(),
260 indices: Cow::Owned(Vec::new()),
261 clusters: MeshClusters::default(),
262 flags: 0,
263 },
264 });
265 let index = scene.meshes.len() - 1;
266 (scene, index)
267 }
268
269 fn flat_vertices<'s>(scene: &'s mut SceneDesc<'_>, mesh: usize) -> &'s mut Vec<u8> {
270 let Geometry::Flat { vertices, .. } = &mut scene.meshes[mesh].geometry else {
271 panic!("mesh {mesh} is flat geometry");
272 };
273 vertices.to_mut()
274 }
275
276 fn assert_close(actual: Vec3, expected: Vec3) {
277 assert!(
278 actual.abs_diff_eq(expected, 1e-6),
279 "{actual} is not {expected}"
280 );
281 }
282
283 #[test]
288 fn a_turned_instance_is_bounded_by_its_vertices() {
289 let (scene, octahedron) = with_mesh(&[
290 [1.0, 0.0, 0.0],
291 [-1.0, 0.0, 0.0],
292 [0.0, 1.0, 0.0],
293 [0.0, -1.0, 0.0],
294 [0.0, 0.0, 1.0],
295 [0.0, 0.0, -1.0],
296 ]);
297 let place = Mat4::from_translation(Vec3::new(1.0, 2.0, 3.0));
298 let instance = InstanceDesc {
299 mesh: octahedron,
300 material: 0,
301 transform: Mat4::from_rotation_z(FRAC_PI_4),
302 };
303 let bounds = scene
304 .instance_bounds(&[instance], place)
305 .expect("finite geometry");
306 assert_close(
307 bounds.min,
308 Vec3::new(1.0 - FRAC_1_SQRT_2, 2.0 - FRAC_1_SQRT_2, 2.0),
309 );
310 assert_close(
311 bounds.max,
312 Vec3::new(1.0 + FRAC_1_SQRT_2, 2.0 + FRAC_1_SQRT_2, 4.0),
313 );
314
315 let loose = Aabb {
316 min: Vec3::splat(-1.0),
317 max: Vec3::ONE,
318 }
319 .transformed(place * instance.transform);
320 assert!(
321 loose.max.x > bounds.max.x + 0.5,
322 "the turned box of the mesh's box is {loose:?}, not the vertex bound"
323 );
324 }
325
326 #[test]
327 fn several_instances_are_bounded_together() {
328 let scene = demo();
329 let bounds = scene
330 .instance_bounds(
331 &[
332 cube(Mat4::from_translation(Vec3::new(-2.0, 0.0, 0.0))),
333 cube(
334 Mat4::from_translation(Vec3::new(3.0, 4.0, 5.0))
335 * Mat4::from_scale(Vec3::new(2.0, 1.0, 3.0)),
336 ),
337 ],
338 Mat4::IDENTITY,
339 )
340 .expect("two cubes");
341 assert_eq!(bounds.min, Vec3::new(-2.5, -0.5, -0.5));
342 assert_eq!(bounds.max, Vec3::new(4.0, 4.5, 6.5));
343 }
344
345 #[test]
349 fn a_nan_vertex_is_refused_and_names_its_instance() {
350 let (mut scene, poisoned) = with_mesh(&[[0.0; 3], [1.0; 3], [2.0; 3]]);
351 let bytes = flat_vertices(&mut scene, poisoned);
352 bytes[2 * mesh::VERTEX_STRIDE..2 * mesh::VERTEX_STRIDE + 4]
353 .copy_from_slice(&f32::NAN.to_le_bytes());
354 let instances = [
355 cube(Mat4::IDENTITY),
356 InstanceDesc {
357 mesh: poisoned,
358 material: 0,
359 transform: Mat4::IDENTITY,
360 },
361 ];
362 let expected = SceneBoundsError::NonFinitePosition {
363 instance: 1,
364 vertex: 2,
365 };
366 assert_eq!(
367 scene.instance_bounds(&instances, Mat4::IDENTITY),
368 Err(expected)
369 );
370 assert_eq!(scene.instance_parts(&instances), Err(expected));
371 assert_eq!(
372 expected.to_string(),
373 "instance 1's vertex 2 is not finite once placed"
374 );
375 }
376
377 #[test]
378 fn a_non_finite_transform_is_refused() {
379 let scene = demo();
380 let nan = Mat4::from_translation(Vec3::new(f32::NAN, 0.0, 0.0));
381 let expected = SceneBoundsError::NonFinitePosition {
382 instance: 0,
383 vertex: 0,
384 };
385 assert_eq!(
386 scene.instance_bounds(&[cube(nan)], Mat4::IDENTITY),
387 Err(expected)
388 );
389 assert_eq!(
390 scene.instance_bounds(&[cube(Mat4::IDENTITY)], nan),
391 Err(expected)
392 );
393 assert_eq!(scene.instance_parts(&[cube(nan)]), Err(expected));
394 let huge = Mat4::from_scale(Vec3::splat(f32::MAX));
396 assert_eq!(
397 scene.instance_bounds(&[cube(huge)], Mat4::from_scale(Vec3::splat(4.0))),
398 Err(expected)
399 );
400 }
401
402 #[test]
403 fn an_empty_set_has_no_bounds_and_no_parts() {
404 let scene = demo();
405 assert_eq!(
406 scene.instance_bounds(&[], Mat4::IDENTITY),
407 Err(SceneBoundsError::Empty)
408 );
409 assert_eq!(scene.instance_parts(&[]), Ok(Vec::new()));
410 }
411
412 #[test]
415 fn an_empty_mesh_contributes_nothing_and_is_no_part() {
416 let (scene, empty) = with_mesh(&[]);
417 let hollow = InstanceDesc {
418 mesh: empty,
419 material: 0,
420 transform: Mat4::IDENTITY,
421 };
422 assert_eq!(
423 scene.instance_bounds(&[hollow], Mat4::IDENTITY),
424 Err(SceneBoundsError::Empty)
425 );
426 assert_eq!(
427 scene.instance_bounds(&[hollow, cube(Mat4::IDENTITY)], Mat4::IDENTITY),
428 Ok(Aabb {
429 min: Vec3::splat(-0.5),
430 max: Vec3::splat(0.5),
431 })
432 );
433 assert_eq!(
434 scene.instance_parts(&[cube(Mat4::IDENTITY), hollow]),
435 Err(SceneBoundsError::EmptyPart { instance: 1 })
436 );
437 }
438
439 #[test]
443 fn the_parts_build_a_compound_a_ray_strikes() {
444 let scene = demo();
445 let parts = scene
446 .instance_parts(&[
447 cube(Mat4::IDENTITY),
448 cube(Mat4::from_translation(Vec3::new(3.0, 0.0, 0.0))),
449 ])
450 .expect("two cubes");
451 let widened: Vec<crcbl_phys::Aabb> = parts
452 .iter()
453 .map(|part| crcbl_phys::Aabb::new(part.min.as_dvec3(), part.max.as_dvec3()))
454 .collect();
455 let compound = AabbCompound::new(&widened).expect("finite, non-inverted parts");
456 let pose = Transform::new(
459 DVec3::new(0.0, 10.0, 0.0),
460 DQuat::from_rotation_z(core::f64::consts::FRAC_PI_2),
461 );
462 let hit = compound
463 .ray_cast(
464 &pose,
465 &Ray::new(DVec3::new(0.0, 11.75, 0.0), DVec3::new(0.0, 1.0, 0.0)),
466 )
467 .expect("the ray starts between the parts and runs into the second");
468 assert_eq!(hit.part, 1);
469 assert!((hit.hit.point - DVec3::new(0.0, 12.5, 0.0)).length() < 1e-9);
470 assert!((hit.hit.t - 0.75).abs() < 1e-9);
471 }
472
473 #[test]
476 fn missing_or_malformed_mesh_geometry_is_refused() {
477 let scene = demo();
478 let missing = InstanceDesc {
479 mesh: scene.meshes.len(),
480 ..cube(Mat4::IDENTITY)
481 };
482 assert_eq!(
483 scene.instance_bounds(&[missing], Mat4::IDENTITY),
484 Err(SceneBoundsError::MissingMesh {
485 instance: 0,
486 mesh: scene.meshes.len(),
487 })
488 );
489
490 let mut incomplete = demo();
491 flat_vertices(&mut incomplete, DEMO_CUBE).pop();
492 assert_eq!(
493 incomplete.instance_bounds(&[cube(Mat4::IDENTITY)], Mat4::IDENTITY),
494 Err(SceneBoundsError::PartialVertex {
495 instance: 0,
496 mesh: DEMO_CUBE,
497 })
498 );
499
500 let mut nonfinite = demo();
501 flat_vertices(&mut nonfinite, DEMO_CUBE)[..4].copy_from_slice(&f32::NAN.to_le_bytes());
502 assert_eq!(
503 nonfinite.instance_bounds(&[cube(Mat4::IDENTITY)], Mat4::IDENTITY),
504 Err(SceneBoundsError::NonFinitePosition {
505 instance: 0,
506 vertex: 0,
507 })
508 );
509 }
510
511 #[test]
512 fn a_mesh_with_no_vertices_alone_has_no_bounds() {
513 let mut scene = demo();
514 flat_vertices(&mut scene, DEMO_CUBE).clear();
515 assert_eq!(
516 scene.instance_bounds(&[cube(Mat4::IDENTITY)], Mat4::IDENTITY),
517 Err(SceneBoundsError::Empty)
518 );
519 }
520
521 #[test]
522 fn a_dag_is_bounded_by_its_finest_level_and_transforms_compose() {
523 let mut dag_scene = demo();
524 let dag_mesh = dag_scene
525 .meshes
526 .iter()
527 .position(|mesh| matches!(mesh.geometry, Geometry::Dag { .. }))
528 .expect("the demo includes a DAG mesh");
529 let instance = InstanceDesc {
530 mesh: dag_mesh,
531 material: 0,
532 transform: Mat4::IDENTITY,
533 };
534 let expected = dag_scene
535 .instance_bounds(&[instance], Mat4::IDENTITY)
536 .expect("the dunes have vertices");
537 {
538 let Geometry::Dag { levels, .. } = &mut dag_scene.meshes[dag_mesh].geometry else {
539 panic!("the selected demo mesh is a DAG");
540 };
541 assert!(levels.len() > 1);
542 for vertex in levels[1]
543 .to_mut()
544 .as_chunks_mut::<{ mesh::VERTEX_STRIDE }>()
545 .0
546 {
547 vertex[..12].copy_from_slice(
548 &[10_000.0_f32, 10_000.0, 10_000.0]
549 .map(f32::to_le_bytes)
550 .concat(),
551 );
552 }
553 }
554 assert_eq!(
555 dag_scene.instance_bounds(&[instance], Mat4::IDENTITY),
556 Ok(expected)
557 );
558
559 let Geometry::Dag { levels, .. } = &mut dag_scene.meshes[dag_mesh].geometry else {
560 panic!("the selected demo mesh is a DAG");
561 };
562 levels.clear();
563 assert_eq!(
564 dag_scene.instance_bounds(&[instance], Mat4::IDENTITY),
565 Err(SceneBoundsError::NoLevels {
566 instance: 0,
567 mesh: dag_mesh,
568 })
569 );
570
571 let scene = demo();
572 let root =
573 Mat4::from_translation(Vec3::new(10.0, 20.0, 30.0)) * Mat4::from_rotation_z(FRAC_PI_2);
574 let bounds = scene
575 .instance_bounds(&[cube(Mat4::from_translation(Vec3::X * 2.0))], root)
576 .expect("a cube");
577 assert_eq!(bounds.min, Vec3::new(9.5, 21.5, 29.5));
578 assert_eq!(bounds.max, Vec3::new(10.5, 22.5, 30.5));
579 }
580
581 #[test]
584 fn parts_follow_each_instance_transform() {
585 let scene = demo();
586 let large_coordinate = f32::MAX * 0.75;
587 let parts = scene
588 .instance_parts(&[
589 cube(Mat4::from_translation(Vec3::new(-2.0, 0.0, 0.0))),
590 cube(
591 Mat4::from_translation(Vec3::new(3.0, 4.0, 5.0))
592 * Mat4::from_scale(Vec3::new(2.0, 1.0, 3.0)),
593 ),
594 cube(Mat4::from_translation(Vec3::splat(large_coordinate))),
595 cube(
596 Mat4::from_translation(Vec3::new(7.0, 8.0, 9.0)) * Mat4::from_scale(Vec3::ZERO),
597 ),
598 ])
599 .expect("four finite cubes");
600 assert_eq!(
601 parts,
602 vec![
603 Aabb {
604 min: Vec3::new(-2.5, -0.5, -0.5),
605 max: Vec3::new(-1.5, 0.5, 0.5),
606 },
607 Aabb {
608 min: Vec3::new(2.0, 3.5, 3.5),
609 max: Vec3::new(4.0, 4.5, 6.5),
610 },
611 Aabb {
612 min: Vec3::splat(large_coordinate),
613 max: Vec3::splat(large_coordinate),
614 },
615 Aabb {
616 min: Vec3::new(7.0, 8.0, 9.0),
617 max: Vec3::new(7.0, 8.0, 9.0),
618 },
619 ]
620 );
621 }
622}