1use core::num::NonZeroU32;
4
5use bevy::prelude::*;
6use parry::shape::{SharedShape, TypedShape};
7use thiserror::Error;
8
9use crate::prelude::*;
10
11#[derive(Debug, Clone)]
52pub struct TrimeshBuilder {
53 pub shape: SharedShape,
55 pub position: RVector,
57 pub rotation: Rot,
59 pub fail_on_compound_error: bool,
62 pub fallback_subdivisions: NonZeroU32,
65 pub sphere_subdivisions: Option<(NonZeroU32, NonZeroU32)>,
68 pub capsule_subdivision: Option<(NonZeroU32, NonZeroU32)>,
71 pub cylinder_subdivisions: Option<NonZeroU32>,
74 pub cone_subdivisions: Option<NonZeroU32>,
77}
78
79#[derive(Debug, Clone, PartialEq, Reflect, Default)]
81pub struct Trimesh {
82 pub vertices: Vec<RVector>,
84 pub indices: Vec<[u32; 3]>,
86}
87
88impl Trimesh {
89 pub fn extend(&mut self, other: Trimesh) {
92 let next_vertex_index = self.vertices.len() as u32;
93 self.vertices.extend(other.vertices);
94 self.indices.extend(
95 other
96 .indices
97 .iter()
98 .map(|is| is.map(|i| i + next_vertex_index)),
99 );
100 }
101}
102
103#[derive(Debug, Error)]
105pub enum TrimeshBuilderError {
106 #[error("Unsupported shape type: {0}")]
108 UnsupportedShape(String),
109}
110
111impl TrimeshBuilder {
112 pub fn new(shape: SharedShape) -> Self {
114 TrimeshBuilder {
115 shape,
116 position: default(),
117 rotation: default(),
118 fail_on_compound_error: true,
119 fallback_subdivisions: 16_u32.try_into().unwrap(),
121 sphere_subdivisions: None,
122 capsule_subdivision: None,
123 cylinder_subdivisions: None,
124 cone_subdivisions: None,
125 }
126 }
127
128 pub fn translated(&mut self, position: RVector) -> &mut Self {
130 self.position += position;
131 self
132 }
133
134 pub fn rotated(&mut self, rotation: impl Into<Rot>) -> &mut Self {
136 self.rotation = rotation.into() * self.rotation;
137 self
138 }
139
140 pub fn fallback_subdivisions(&mut self, subdivisions: impl TryInto<NonZeroU32>) -> &mut Self {
143 self.fallback_subdivisions = subdivisions
144 .try_into()
145 .unwrap_or_else(|_| panic!("Fallback subdivision count must be non-zero"));
146 self
147 }
148
149 pub fn sphere_subdivisions(
152 &mut self,
153 theta: impl TryInto<NonZeroU32>,
154 phi: impl TryInto<NonZeroU32>,
155 ) -> &mut Self {
156 self.sphere_subdivisions = Some((
157 theta
158 .try_into()
159 .unwrap_or_else(|_| panic!("Sphere theta subdivisions must be non-zero")),
160 phi.try_into()
161 .inspect(|phi| {
162 assert!(phi.get() >= 2, "Sphere phi subdivisions must be at least 2")
163 })
164 .unwrap_or_else(|_| panic!("Sphere phi subdivisions must be non-zero")),
165 ));
166 self
167 }
168
169 pub fn capsule_subdivisions(
172 &mut self,
173 theta: impl TryInto<NonZeroU32>,
174 phi: impl TryInto<NonZeroU32>,
175 ) -> &mut Self {
176 self.capsule_subdivision = Some((
177 theta
178 .try_into()
179 .unwrap_or_else(|_| panic!("Capsule theta subdivisions must be non-zero")),
180 phi.try_into()
181 .inspect(|phi| {
182 assert!(
183 phi.get() >= 2,
184 "Capsule phi subdivisions must be at least 2"
185 )
186 })
187 .unwrap_or_else(|_| panic!("Capsule phi subdivisions must be non-zero")),
188 ));
189 self
190 }
191
192 pub fn cylinder_subdivisions(&mut self, subdivisions: impl TryInto<NonZeroU32>) -> &mut Self {
194 self.cylinder_subdivisions = Some(
195 subdivisions
196 .try_into()
197 .unwrap_or_else(|_| panic!("Cylinder subdivisions must be non-zero")),
198 );
199 self
200 }
201
202 pub fn cone_subdivisions(&mut self, subdivisions: impl TryInto<NonZeroU32>) -> &mut Self {
204 self.cone_subdivisions = Some(
205 subdivisions
206 .try_into()
207 .unwrap_or_else(|_| panic!("Cone subdivisions must be non-zero")),
208 );
209 self
210 }
211
212 pub fn fail_on_compound_error(&mut self, fail_on_compound_error: bool) -> &mut Self {
215 self.fail_on_compound_error = fail_on_compound_error;
216 self
217 }
218
219 fn subdivisions(&self, get: impl Fn(&Self) -> Option<NonZeroU32>) -> u32 {
220 get(self).unwrap_or(self.fallback_subdivisions).into()
221 }
222
223 pub fn build(&self) -> Result<Trimesh, TrimeshBuilderError> {
229 let (vertices, indices) = match self.shape.as_typed_shape() {
230 TypedShape::Cuboid(cuboid) => cuboid.to_trimesh(),
232 TypedShape::Voxels(voxels) => voxels.to_trimesh(),
233 TypedShape::ConvexPolyhedron(convex_polyhedron) => convex_polyhedron.to_trimesh(),
234 TypedShape::HeightField(height_field) => height_field.to_trimesh(),
235 TypedShape::Triangle(triangle) => {
237 (vec![triangle.a, triangle.b, triangle.c], vec![[0, 1, 2]])
238 }
239 TypedShape::TriMesh(tri_mesh) => {
240 (tri_mesh.vertices().to_vec(), tri_mesh.indices().to_vec())
241 }
242 TypedShape::Ball(ball) => ball.to_trimesh(
244 self.subdivisions(|t| t.sphere_subdivisions?.0.into()),
245 self.subdivisions(|t| t.sphere_subdivisions?.1.into()),
246 ),
247 TypedShape::Capsule(capsule) => capsule.to_trimesh(
248 self.subdivisions(|t| t.capsule_subdivision?.0.into()),
249 self.subdivisions(|t| t.capsule_subdivision?.1.into()),
250 ),
251 TypedShape::Cylinder(cylinder) => {
252 cylinder.to_trimesh(self.subdivisions(|t| t.cylinder_subdivisions))
253 }
254 TypedShape::Cone(cone) => cone.to_trimesh(self.subdivisions(|t| t.cone_subdivisions)),
255 TypedShape::Compound(compound) => {
257 let mut sub_builder = self.clone();
258 let rot = self.rotation.real();
259 return compound.shapes().iter().try_fold(
260 Trimesh::default(),
261 move |mut compound_trimesh, (sub_pos, shape)| {
262 sub_builder.shape = shape.clone();
263 sub_builder.position = self.position + rot * sub_pos.translation;
264 sub_builder.rotation =
265 self.rotation.mul_quat(sub_pos.rotation.f32()).normalize();
266 let trimesh = match sub_builder.build() {
267 Ok(trimesh) => trimesh,
268 Err(error) => {
269 return if self.fail_on_compound_error {
270 Err(error)
271 } else {
272 Ok(compound_trimesh)
273 };
274 }
275 };
276
277 compound_trimesh.extend(trimesh);
278
279 Ok(compound_trimesh)
281 },
282 );
283 }
284 TypedShape::RoundCuboid(round_shape) => round_shape.inner_shape.to_trimesh(),
286 TypedShape::RoundTriangle(round_shape) => (
287 vec![
288 round_shape.inner_shape.a,
289 round_shape.inner_shape.b,
290 round_shape.inner_shape.c,
291 ],
292 vec![[0, 1, 2]],
293 ),
294 TypedShape::RoundConvexPolyhedron(round_shape) => round_shape.inner_shape.to_trimesh(),
295 TypedShape::RoundCylinder(round_shape) => round_shape
296 .inner_shape
297 .to_trimesh(self.subdivisions(|t| t.cylinder_subdivisions)),
298 TypedShape::RoundCone(round_shape) => round_shape
299 .inner_shape
300 .to_trimesh(self.subdivisions(|t| t.cone_subdivisions)),
301 TypedShape::Segment(segment) => {
303 return Err(TrimeshBuilderError::UnsupportedShape(format!(
304 "{segment:?}",
305 )));
306 }
307 TypedShape::Polyline(polyline) => {
308 return Err(TrimeshBuilderError::UnsupportedShape(format!(
309 "{polyline:?}",
310 )));
311 }
312 TypedShape::HalfSpace(half_space) => {
313 return Err(TrimeshBuilderError::UnsupportedShape(format!(
314 "{half_space:?}",
315 )));
316 }
317 TypedShape::Custom(_shape) => {
318 return Err(TrimeshBuilderError::UnsupportedShape("Custom".to_string()));
319 }
320 };
321 let pos = self.position;
322 let rot = self.rotation.real();
323 Ok(Trimesh {
324 vertices: vertices.into_iter().map(|v| pos + rot * v).collect(),
325 indices,
326 })
327 }
328}
329
330impl Collider {
331 pub fn trimesh_builder(&self) -> TrimeshBuilder {
333 TrimeshBuilder::new(self.shape_scaled().clone())
334 }
335}
336
337#[cfg(feature = "collider-from-mesh")]
338impl From<Trimesh> for Mesh {
339 fn from(trimesh: Trimesh) -> Self {
340 use bevy::asset::RenderAssetUsages;
341 use bevy::mesh::{Indices, PrimitiveTopology, VertexAttributeValues, prelude::*};
342
343 let mut mesh = Mesh::new(
344 PrimitiveTopology::TriangleList,
345 RenderAssetUsages::default(),
346 );
347 mesh.insert_attribute(
348 Mesh::ATTRIBUTE_POSITION,
349 VertexAttributeValues::Float32x3(
350 trimesh
351 .vertices
352 .into_iter()
353 .map(|v| v.f32().to_array())
354 .collect(),
355 ),
356 );
357 mesh.insert_indices(Indices::U32(
358 trimesh.indices.into_iter().flatten().collect(),
359 ));
360 mesh.compute_normals();
361 if let Err(err) = mesh.generate_tangents() {
362 warn!("Failed to generate tangents for mesh: {err}");
363 }
364
365 mesh
366 }
367}
368
369#[cfg(test)]
370mod tests {
371 use approx::assert_relative_eq;
372 use bevy_math::DVec3;
373
374 use super::*;
375
376 #[test]
377 fn rasterizes_cuboid() {
378 let collider = Collider::cuboid(1.0, 2.0, 3.0);
379 let trimesh = collider.trimesh_builder().build().unwrap();
380 assert_eq!(trimesh.vertices.len(), 8);
381 assert_eq!(trimesh.indices.len(), 12);
382 }
383
384 #[test]
385 fn rasterizes_compound() {
386 let a = Collider::cuboid(1.0, 2.0, 3.0);
387 let b = Collider::sphere(0.4);
388 let collider = Collider::compound(vec![
389 (RVector::new(1.0, 2.0, 3.0), Quat::from_rotation_z(0.2), a),
390 (
391 RVector::new(-12.0, 4.0, -0.01),
392 Quat::from_rotation_x(0.1),
393 b,
394 ),
395 ]);
396 let trimesh = collider
397 .trimesh_builder()
398 .fallback_subdivisions(2)
399 .translated(RVector::new(3.0, -2.0, 0.0))
400 .rotated(Quat::from_rotation_y(-3.0))
401 .build()
402 .unwrap();
403 let expected_vertices = vec![
404 DVec3::new(1.663415604680207, -1.0794012104819937, -4.354963570435039).real(),
405 DVec3::new(2.0867756033225007, -1.0794012104819934, -1.3849860769934488).real(),
406 DVec3::new(1.116517045301514, -0.8807318727109547, -1.246679082171598).real(),
407 DVec3::new(0.6931570466592203, -0.8807318727109547, -4.216656575613189).real(),
408 DVec3::new(2.056777912558161, 0.8807319423722882, -4.411036004147714).real(),
409 DVec3::new(2.4801379112004547, 0.8807319423722882, -1.4410585107061238).real(),
410 DVec3::new(1.5098793531794679, 1.0794012801433273, -1.302751515884273).real(),
411 DVec3::new(1.086519354537174, 1.079401280143327, -4.272729009325864).real(),
412 DVec3::new(14.886956777274035, 1.6019984034862897, -1.6440063661356903).real(),
413 DVec3::new(14.485324381553463, 2.0000000696613336, -1.6270920990914757).real(),
414 DVec3::new(15.277318379804553, 2.0000000696613336, -1.739988098729421).real(),
415 DVec3::new(14.875685984083981, 2.3980017358363774, -1.7230738316852063).real(),
416 ];
417 trimesh
418 .vertices
419 .iter()
420 .zip(expected_vertices.iter())
421 .for_each(|(v, expected)| assert_relative_eq!(*v, *expected, epsilon = 1e-6));
422 assert_eq!(
423 trimesh.indices,
424 vec![
425 [4, 5, 0],
426 [5, 1, 0],
427 [5, 6, 1],
428 [6, 2, 1],
429 [6, 7, 3],
430 [2, 6, 3],
431 [7, 4, 0],
432 [3, 7, 0],
433 [0, 1, 2],
434 [3, 0, 2],
435 [7, 6, 5],
436 [4, 7, 5],
437 [8, 9, 10],
438 [8, 10, 9],
439 [9, 11, 10],
440 [10, 11, 9],
441 ]
442 );
443 }
444}