1use glam::{Vec2, Vec3};
4use std::fmt;
5
6pub const MAX_INDEXED_VERTICES: usize = u16::MAX as usize;
8pub const MAX_MESH_VERTICES: usize = i32::MAX as usize / size_of::<[f32; 3]>();
10
11#[derive(Clone, Debug, Default)]
18pub struct MeshData {
19 pub positions: Vec<Vec3>,
21 pub normals: Option<Vec<Vec3>>,
23 pub texcoords: Option<Vec<Vec2>>,
25 pub colors: Option<Vec<[u8; 4]>>,
27 pub indices: Option<Vec<u16>>,
29}
30
31#[derive(Clone, Copy, Debug, PartialEq, Eq)]
33pub struct MeshInfo {
34 pub vertex_count: usize,
36 pub triangle_count: usize,
38}
39
40#[derive(Clone, Copy, Debug, PartialEq, Eq)]
42pub enum MeshAttribute {
43 Positions,
45 Normals,
47 Texcoords,
49 Colors,
51}
52
53#[derive(Clone, Debug, PartialEq, Eq)]
55pub enum MeshError {
56 Empty,
58 TooLarge,
60 IncompleteTriangle,
62 AttributeLength {
64 attribute: MeshAttribute,
66 expected: usize,
68 actual: usize,
70 },
71 NonFinite {
73 attribute: MeshAttribute,
75 vertex: usize,
77 },
78 IndexOutOfBounds {
80 offset: usize,
82 index: u16,
84 vertex_count: usize,
86 },
87}
88
89impl fmt::Display for MeshError {
90 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
91 match self {
92 Self::Empty => write!(f, "mesh must contain vertices and at least one triangle"),
93 Self::TooLarge => write!(
94 f,
95 "mesh exceeds backend limits; split it into smaller meshes"
96 ),
97 Self::IncompleteTriangle => write!(f, "triangle stream length must be a multiple of 3"),
98 Self::AttributeLength {
99 attribute,
100 expected,
101 actual,
102 } => write!(
103 f,
104 "{attribute:?} has {actual} elements; expected {expected}"
105 ),
106 Self::NonFinite { attribute, vertex } => {
107 write!(f, "{attribute:?} vertex {vertex} contains NaN or infinity")
108 }
109 Self::IndexOutOfBounds {
110 offset,
111 index,
112 vertex_count,
113 } => write!(
114 f,
115 "index {offset} references vertex {index}; only {vertex_count} vertices exist"
116 ),
117 }
118 }
119}
120
121impl std::error::Error for MeshError {}
122
123impl MeshData {
124 pub fn new(positions: Vec<Vec3>) -> Self {
126 Self {
127 positions,
128 ..Self::default()
129 }
130 }
131
132 pub fn validate(&self) -> Result<MeshInfo, MeshError> {
137 let vertex_count = self.positions.len();
138 let stream_len = self.indices.as_ref().map_or(vertex_count, Vec::len);
139 validate_counts(vertex_count, stream_len, self.indices.is_some())?;
140 for (attribute, actual) in [
141 (MeshAttribute::Normals, self.normals.as_ref().map(Vec::len)),
142 (
143 MeshAttribute::Texcoords,
144 self.texcoords.as_ref().map(Vec::len),
145 ),
146 (MeshAttribute::Colors, self.colors.as_ref().map(Vec::len)),
147 ] {
148 if let Some(actual) = actual.filter(|&len| len != vertex_count) {
149 return Err(MeshError::AttributeLength {
150 attribute,
151 expected: vertex_count,
152 actual,
153 });
154 }
155 }
156 check_finite(
157 MeshAttribute::Positions,
158 self.positions.iter().map(|v| v.is_finite()),
159 )?;
160 if let Some(normals) = &self.normals {
161 check_finite(
162 MeshAttribute::Normals,
163 normals.iter().map(|v| v.is_finite()),
164 )?;
165 }
166 if let Some(texcoords) = &self.texcoords {
167 check_finite(
168 MeshAttribute::Texcoords,
169 texcoords.iter().map(|v| v.is_finite()),
170 )?;
171 }
172 if let Some(indices) = &self.indices
173 && let Some((offset, &index)) = indices
174 .iter()
175 .enumerate()
176 .find(|(_, i)| usize::from(**i) >= vertex_count)
177 {
178 return Err(MeshError::IndexOutOfBounds {
179 offset,
180 index,
181 vertex_count,
182 });
183 }
184 Ok(MeshInfo {
185 vertex_count,
186 triangle_count: stream_len / 3,
187 })
188 }
189}
190
191fn validate_counts(vertices: usize, stream: usize, indexed: bool) -> Result<(), MeshError> {
192 if vertices == 0 || stream == 0 {
193 return Err(MeshError::Empty);
194 }
195 if vertices > MAX_MESH_VERTICES
196 || (indexed
197 && (vertices > MAX_INDEXED_VERTICES || stream > i32::MAX as usize / size_of::<u16>()))
198 {
199 return Err(MeshError::TooLarge);
200 }
201 if !stream.is_multiple_of(3) {
202 return Err(MeshError::IncompleteTriangle);
203 }
204 Ok(())
205}
206
207fn check_finite(
208 attribute: MeshAttribute,
209 mut values: impl Iterator<Item = bool>,
210) -> Result<(), MeshError> {
211 if let Some(vertex) = values.position(|finite| !finite) {
212 Err(MeshError::NonFinite { attribute, vertex })
213 } else {
214 Ok(())
215 }
216}
217
218#[cfg(test)]
219mod tests {
220 use super::*;
221
222 fn triangle() -> MeshData {
223 MeshData::new(vec![Vec3::ZERO, Vec3::X, Vec3::Y])
224 }
225
226 #[test]
227 fn indexed_quad_and_unindexed_triangle() {
228 assert_eq!(
229 triangle().validate().unwrap(),
230 MeshInfo {
231 vertex_count: 3,
232 triangle_count: 1
233 }
234 );
235 let mesh = MeshData {
236 positions: vec![Vec3::ZERO, Vec3::X, Vec3::ONE, Vec3::Y],
237 indices: Some(vec![0, 1, 2, 0, 2, 3]),
238 normals: Some(vec![Vec3::Z; 4]),
239 texcoords: Some(vec![Vec2::splat(2.0); 4]),
240 colors: Some(vec![[255; 4]; 4]),
241 };
242 assert_eq!(
243 mesh.validate().unwrap(),
244 MeshInfo {
245 vertex_count: 4,
246 triangle_count: 2
247 }
248 );
249 }
250
251 #[test]
252 fn rejects_empty_and_incomplete_streams() {
253 assert_eq!(MeshData::default().validate(), Err(MeshError::Empty));
254 let mut mesh = triangle();
255 mesh.positions.pop();
256 assert_eq!(mesh.validate(), Err(MeshError::IncompleteTriangle));
257 mesh.indices = Some(vec![]);
258 assert_eq!(mesh.validate(), Err(MeshError::Empty));
259 mesh.indices = Some(vec![0, 1]);
260 assert_eq!(mesh.validate(), Err(MeshError::IncompleteTriangle));
261 }
262
263 #[test]
264 fn checks_optional_lengths_and_all_float_channels() {
265 for attribute in [
266 MeshAttribute::Normals,
267 MeshAttribute::Texcoords,
268 MeshAttribute::Colors,
269 ] {
270 let mut mesh = triangle();
271 match attribute {
272 MeshAttribute::Normals => mesh.normals = Some(vec![]),
273 MeshAttribute::Texcoords => mesh.texcoords = Some(vec![Vec2::ZERO]),
274 MeshAttribute::Colors => mesh.colors = Some(vec![[0; 4]; 4]),
275 MeshAttribute::Positions => unreachable!(),
276 }
277 assert!(
278 matches!(mesh.validate(), Err(MeshError::AttributeLength { attribute: a, expected: 3, .. }) if a == attribute)
279 );
280 }
281 for invalid in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
282 for attribute in [
283 MeshAttribute::Positions,
284 MeshAttribute::Normals,
285 MeshAttribute::Texcoords,
286 ] {
287 let mut mesh = triangle();
288 match attribute {
289 MeshAttribute::Positions => mesh.positions[1].x = invalid,
290 MeshAttribute::Normals => {
291 mesh.normals = Some(vec![Vec3::ZERO, Vec3::splat(invalid), Vec3::ZERO])
292 }
293 MeshAttribute::Texcoords => {
294 mesh.texcoords = Some(vec![Vec2::ZERO, Vec2::splat(invalid), Vec2::ZERO])
295 }
296 MeshAttribute::Colors => unreachable!(),
297 }
298 assert_eq!(
299 mesh.validate(),
300 Err(MeshError::NonFinite {
301 attribute,
302 vertex: 1
303 })
304 );
305 }
306 }
307 }
308
309 #[test]
310 fn validates_index_bounds_and_backend_count_limits() {
311 let mut mesh = triangle();
312 mesh.indices = Some(vec![0, 1, 3]);
313 assert_eq!(
314 mesh.validate(),
315 Err(MeshError::IndexOutOfBounds {
316 offset: 2,
317 index: 3,
318 vertex_count: 3
319 })
320 );
321 mesh.positions = vec![Vec3::ZERO; MAX_INDEXED_VERTICES];
322 mesh.indices = Some(vec![0, 1, u16::MAX - 1]);
323 assert!(mesh.validate().is_ok());
324 mesh.positions.push(Vec3::ZERO);
325 assert_eq!(mesh.validate(), Err(MeshError::TooLarge));
326 assert_eq!(
327 validate_counts(MAX_MESH_VERTICES + 1, 3, false),
328 Err(MeshError::TooLarge)
329 );
330 assert_eq!(
331 validate_counts(3, i32::MAX as usize / 2 + 1, true),
332 Err(MeshError::TooLarge)
333 );
334 assert!(validate_counts(MAX_MESH_VERTICES, 3, false).is_ok());
335 }
336
337 #[test]
338 fn mesh_data_can_cross_threads() {
339 let info = std::thread::spawn(|| triangle().validate())
340 .join()
341 .unwrap()
342 .unwrap();
343 assert_eq!(info.triangle_count, 1);
344 }
345}