off_rs/geometry/
mesh.rs

1use super::{color::Color, position::Position};
2
3/// Represents a vertex of a mesh.
4/// A vertex contains a position and optionally a vertex color.
5#[derive(Copy, Clone, PartialEq, Debug, Default)]
6pub struct Vertex {
7    /// The position of the vertex.
8    pub position: Position,
9    /// The color of the vertex.
10    pub color: Option<Color>,
11}
12
13impl Vertex {
14    /// Creates a new [`Vertex`].
15    #[must_use]
16    pub fn new(position: Position, color: Option<Color>) -> Self {
17        Self { position, color }
18    }
19}
20
21/// Represents a face of a mesh.
22/// A face contains a list of vertex indicies and optionally a color.
23#[derive(Clone, PartialEq, Debug, Default)]
24pub struct Face {
25    /// The list of vertex indicies that make up the face.
26    pub vertices: Vec<usize>,
27    /// The color of the face.
28    pub color: Option<Color>,
29}
30
31impl Face {
32    /// Creates a new [`Face`].
33    #[must_use]
34    pub fn new(vertices: Vec<usize>, color: Option<Color>) -> Self {
35        Self { vertices, color }
36    }
37}
38
39impl From<Face> for Vec<usize> {
40    /// Converts a [`Face`] to a [`Vec<usize>`] containing the vertex indicies.
41    fn from(value: Face) -> Vec<usize> {
42        value.vertices
43    }
44}
45
46/// Represents a mesh.
47/// A mesh contains a list of vertices and a list of faces.
48#[derive(Default, Clone, PartialEq, Debug)]
49pub struct Mesh {
50    /// The list of vertices.
51    pub vertices: Vec<Vertex>,
52    /// The list of faces.
53    pub faces: Vec<Face>,
54}
55
56impl Mesh {
57    /// Creates a new [`Mesh`].
58    #[must_use]
59    pub(crate) fn new() -> Self {
60        Self::default()
61    }
62
63    /// Returns the number of vertices in the mesh.
64    #[must_use]
65    pub fn vertex_count(&self) -> usize {
66        self.vertices.len()
67    }
68
69    /// Returns the number of faces in the mesh.
70    #[must_use]
71    pub fn face_count(&self) -> usize {
72        self.faces.len()
73    }
74
75    /// Calculates the number of edges in the mesh.
76    #[must_use]
77    pub fn edge_count(&self) -> usize {
78        self.faces.iter().map(|face| face.vertices.len() - 1).sum()
79    }
80}