bevy_mesh/primitives/dim3/
tetrahedron.rs

1use super::triangle3d;
2use crate::{Indices, Mesh, MeshBuilder, Meshable, PrimitiveTopology};
3use bevy_asset::RenderAssetUsages;
4use bevy_math::primitives::{Tetrahedron, Triangle3d};
5use bevy_reflect::prelude::*;
6
7/// A builder used for creating a [`Mesh`] with a [`Tetrahedron`] shape.
8#[derive(Clone, Copy, Debug, Default, Reflect)]
9#[reflect(Default, Debug, Clone)]
10pub struct TetrahedronMeshBuilder {
11    tetrahedron: Tetrahedron,
12}
13
14impl MeshBuilder for TetrahedronMeshBuilder {
15    fn build(&self) -> Mesh {
16        let mut faces: Vec<_> = self.tetrahedron.faces().into();
17
18        // If the tetrahedron has negative orientation, reverse all the triangles so that
19        // they still face outward.
20        if self.tetrahedron.signed_volume().is_sign_negative() {
21            faces.iter_mut().for_each(Triangle3d::reverse);
22        }
23
24        let mut positions = vec![];
25        let mut normals = vec![];
26        let mut uvs = vec![];
27
28        // Each face is meshed as a `Triangle3d`, and we just shove the data into the
29        // vertex attributes sequentially.
30        for face in faces {
31            positions.extend(face.vertices);
32
33            let face_normal = triangle3d::normal_vec(&face);
34            normals.extend(vec![face_normal; 3]);
35
36            let face_uvs = triangle3d::uv_coords(&face);
37            uvs.extend(face_uvs);
38        }
39
40        // There are four faces and none of them share vertices.
41        let indices = Indices::U32(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]);
42
43        Mesh::new(
44            PrimitiveTopology::TriangleList,
45            RenderAssetUsages::default(),
46        )
47        .with_inserted_indices(indices)
48        .with_inserted_attribute(Mesh::ATTRIBUTE_POSITION, positions)
49        .with_inserted_attribute(Mesh::ATTRIBUTE_NORMAL, normals)
50        .with_inserted_attribute(Mesh::ATTRIBUTE_UV_0, uvs)
51    }
52}
53
54impl Meshable for Tetrahedron {
55    type Output = TetrahedronMeshBuilder;
56
57    fn mesh(&self) -> Self::Output {
58        TetrahedronMeshBuilder { tetrahedron: *self }
59    }
60}
61
62impl From<Tetrahedron> for Mesh {
63    fn from(tetrahedron: Tetrahedron) -> Self {
64        tetrahedron.mesh().build()
65    }
66}