Skip to main content

avian3d/collision/collider/
trimesh_builder.rs

1//! Types used for creating triangle meshes from [`Collider`]s.
2
3use core::num::NonZeroU32;
4
5use bevy::prelude::*;
6use parry::shape::{SharedShape, TypedShape};
7use thiserror::Error;
8
9use crate::prelude::*;
10
11/// An ergonomic builder for triangle meshes from [`Collider`]s.
12///
13/// The builder can configure different subdivision levels for different shapes.
14/// If a shape was not explicitly configured, the builder will use [`Self::fallback_subdivisions`].
15///
16/// Shapes with rounded corners such as [`Collider::round_cuboid`] will be subdivided as if they were not rounded.
17///
18/// # Example
19///
20/// ```
21/// # use avian3d::{prelude::*, math::RVector};
22///
23/// let collider = Collider::sphere(1.0);
24///
25/// // Using default settings
26/// let trimesh = collider.trimesh_builder().build().unwrap();
27///
28/// // Using extra subdivisions
29/// let trimesh = collider
30///     .trimesh_builder()
31///     .sphere_subdivisions(20, 20)
32///     .build()
33///     .unwrap();
34///
35/// // Setting different subdivisions for different shapes
36/// let trimesh = collider
37///     .trimesh_builder()
38///     .sphere_subdivisions(20, 20)
39///     .capsule_subdivisions(10, 5)
40///     .fallback_subdivisions(15)
41///     .build()
42///     .unwrap();
43///
44/// // Generating the trimesh with a transformation
45/// let trimesh = collider
46///     .trimesh_builder()
47///     .translated(RVector::new(1.0, 0.0, 0.0))
48///     .build()
49///     .unwrap();
50/// ```
51#[derive(Debug, Clone)]
52pub struct TrimeshBuilder {
53    /// The shape to be converted into a triangle mesh.
54    pub shape: SharedShape,
55    /// The position of the shape. The default is [0, 0, 0].
56    pub position: RVector,
57    /// The rotation of the shape. The default is the identity rotation.
58    pub rotation: Rot,
59    /// Whether a failure to trimesh a subshape in a compound shape should fail the entire build process.
60    /// Default is true.
61    pub fail_on_compound_error: bool,
62    /// The number of subdivisions to use for shapes that do not have a specific subdivision count.
63    /// Default is 16.
64    pub fallback_subdivisions: NonZeroU32,
65    /// The number of subdivisions for shapes that derive from a sphere.
66    /// Default is None.
67    pub sphere_subdivisions: Option<(NonZeroU32, NonZeroU32)>,
68    /// The number of subdivisions for shapes that derive from a capsule.
69    /// Default is None.
70    pub capsule_subdivision: Option<(NonZeroU32, NonZeroU32)>,
71    /// The number of subdivisions for shapes that derive from a cylinder.
72    /// Default is None.
73    pub cylinder_subdivisions: Option<NonZeroU32>,
74    /// The number of subdivisions for shapes that derive from a cone.
75    /// Default is None.
76    pub cone_subdivisions: Option<NonZeroU32>,
77}
78
79/// A generic triangle mesh representation.
80#[derive(Debug, Clone, PartialEq, Reflect, Default)]
81pub struct Trimesh {
82    /// The vertices of the mesh.
83    pub vertices: Vec<RVector>,
84    /// The triangle indices in counterclockwise winding.
85    pub indices: Vec<[u32; 3]>,
86}
87
88impl Trimesh {
89    /// Extends the trimesh with the vertices and indices of another trimesh.
90    /// The indices of `other` will be offset by the number of vertices in `self`.
91    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/// An error that can occur when building a triangle mesh with [`TrimeshBuilder::build`].
104#[derive(Debug, Error)]
105pub enum TrimeshBuilderError {
106    /// The shape is not supported by the builder.
107    #[error("Unsupported shape type: {0}")]
108    UnsupportedShape(String),
109}
110
111impl TrimeshBuilder {
112    /// Creates a new [`TrimeshBuilder`] for the given shape. Usually you'll want to call [`Collider::trimesh_builder`] instead.
113    pub fn new(shape: SharedShape) -> Self {
114        TrimeshBuilder {
115            shape,
116            position: default(),
117            rotation: default(),
118            fail_on_compound_error: true,
119            // arbitrary number
120            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    /// Translates the mesh. Subsequent calls to this method will add to the previous translation.
129    pub fn translated(&mut self, position: RVector) -> &mut Self {
130        self.position += position;
131        self
132    }
133
134    /// Rotates the mesh. Subsequent calls to this method will add to the previous rotation.
135    pub fn rotated(&mut self, rotation: impl Into<Rot>) -> &mut Self {
136        self.rotation = rotation.into() * self.rotation;
137        self
138    }
139
140    /// Sets the fallback subdivision count for shapes that don't have a specific subdivision count.
141    /// Default is 16.
142    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    /// Sets the subdivision count for sphere shapes. `theta` is the number of subdivisions along the
150    /// latitude, and `phi` is the number of subdivisions along the longitude.
151    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    /// Sets the subdivision count for capsule shapes. `theta` is the number of subdivisions along the
170    /// latitude, and `phi` is the number of subdivisions along the longitude.
171    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    /// Sets the subdivision count for cylinder shapes.
193    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    /// Sets the subdivision count for cone shapes.
203    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    /// Whether a failure to trimesh a subshape in a compound shape should fail the entire build process.
213    /// Default is true.
214    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    /// Builds the trimesh from the configured settings.
224    ///
225    /// Returns an error if the shape is not supported.
226    /// If the shape is a compound, errors in a subshape will either be ignored or fail the entire build process
227    /// depending on the value of [`Self::fail_on_compound_error`].
228    pub fn build(&self) -> Result<Trimesh, TrimeshBuilderError> {
229        let (vertices, indices) = match self.shape.as_typed_shape() {
230            // Simple cases
231            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            // Triangles
236            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            // Need subdivisions
243            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            // Compounds need to be unpacked
256            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                        // No need to track recursive compounds because parry panics on nested compounds anyways lol
280                        Ok(compound_trimesh)
281                    },
282                );
283            }
284            // Rounded shapes ignore the rounding and use the inner shape
285            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            // Not supported
302            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    /// Create a [`TrimeshBuilder`] for building a [`Trimesh`].
332    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}