1use std::{
2 f32::consts::PI,
3 fmt,
4 sync::{OnceLock, atomic::Ordering},
5};
6
7use portable_atomic::AtomicU64;
8
9use super::math::{Mat4, Vec3};
10
11static NEXT_MESH_ID: AtomicU64 = AtomicU64::new(1);
12
13#[derive(Clone, Copy, Debug, PartialEq, Eq)]
15pub enum MeshError {
16 AttributeCountMismatch,
19 IndicesNotTriangles,
21 IndexOutOfRange,
23 Empty,
25}
26
27impl fmt::Display for MeshError {
28 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
29 f.write_str(match self {
30 Self::AttributeCountMismatch => {
31 "texture coordinates and normals need one entry for each position"
32 }
33 Self::IndicesNotTriangles => "the index count is not a multiple of three",
34 Self::IndexOutOfRange => "an index names a vertex past the last one",
35 Self::Empty => "the mesh has no triangle",
36 })
37 }
38}
39
40impl std::error::Error for MeshError {}
41
42#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
45pub enum TextureEdges {
46 #[default]
50 Seams,
51 Outline,
55}
56
57#[derive(Clone, Copy, Debug, PartialEq)]
59pub struct MeshHit {
60 pub distance: f32,
62 pub triangle: u32,
64 pub uv: [f32; 2],
66}
67
68#[derive(Clone, Copy, Debug, PartialEq)]
70pub struct MeshContact {
71 pub point: Vec3,
73 pub distance: f32,
75 pub uv: [f32; 2],
77}
78
79pub struct Mesh {
100 id: u64,
101 positions: Vec<[f32; 3]>,
102 normals: Vec<[f32; 3]>,
103 uvs: Vec<[f32; 2]>,
104 indices: Vec<u32>,
105 texture_edges: TextureEdges,
106 texture_plane: OnceLock<Option<TexturePlane>>,
107 bounds: OnceLock<(Vec3, Vec3)>,
108}
109
110impl PartialEq for Mesh {
111 fn eq(&self, other: &Self) -> bool {
112 self.id == other.id
113 }
114}
115
116impl fmt::Debug for Mesh {
117 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
118 f.debug_struct("Mesh")
119 .field("id", &self.id)
120 .field("vertices", &self.positions.len())
121 .field("triangles", &self.triangle_count())
122 .finish()
123 }
124}
125
126#[derive(Clone, Copy, Debug, PartialEq)]
130pub struct TexturePlane {
131 pub origin: Vec3,
133 pub u_axis: Vec3,
135 pub v_axis: Vec3,
137}
138
139impl Mesh {
140 pub fn new(
144 positions: Vec<[f32; 3]>,
145 uvs: Vec<[f32; 2]>,
146 normals: Option<Vec<[f32; 3]>>,
147 indices: Vec<u32>,
148 ) -> Result<Self, MeshError> {
149 if uvs.len() != positions.len()
150 || normals
151 .as_ref()
152 .is_some_and(|normals| normals.len() != positions.len())
153 {
154 return Err(MeshError::AttributeCountMismatch);
155 }
156 if !indices.len().is_multiple_of(3) {
157 return Err(MeshError::IndicesNotTriangles);
158 }
159 if indices.is_empty() {
160 return Err(MeshError::Empty);
161 }
162 if indices
163 .iter()
164 .any(|&index| index as usize >= positions.len())
165 {
166 return Err(MeshError::IndexOutOfRange);
167 }
168 let normals = normals.unwrap_or_else(|| smooth_normals(&positions, &indices));
169 Ok(Self::assembled(positions, uvs, normals, indices))
170 }
171
172 pub fn plane() -> Self {
176 let mut parts = MeshParts::default();
177 parts.quad(
178 Vec3::ZERO,
179 Vec3::new(1.0, 0.0, 0.0),
180 Vec3::new(0.0, 1.0, 0.0),
181 );
182 parts.into_mesh().with_texture_edges(TextureEdges::Outline)
183 }
184
185 #[must_use]
191 pub fn with_texture_edges(mut self, edges: TextureEdges) -> Self {
192 self.texture_edges = edges;
193 self
194 }
195
196 pub fn texture_edges(&self) -> TextureEdges {
198 self.texture_edges
199 }
200
201 pub fn cuboid() -> Self {
205 let mut parts = MeshParts::default();
206 let (x, y, z) = (
207 Vec3::new(1.0, 0.0, 0.0),
208 Vec3::new(0.0, 1.0, 0.0),
209 Vec3::new(0.0, 0.0, 1.0),
210 );
211 let h = 0.5;
212 parts.quad(Vec3::new(-h, -h, -h), x, y);
213 parts.quad(Vec3::new(h, -h, h), -x, y);
214 parts.quad(Vec3::new(-h, -h, h), -z, y);
215 parts.quad(Vec3::new(h, -h, -h), z, y);
216 parts.quad(Vec3::new(-h, -h, h), x, -z);
217 parts.quad(Vec3::new(-h, h, -h), x, z);
218 parts.into_mesh()
219 }
220
221 pub fn sphere(segments: u32, rings: u32) -> Self {
226 let (segments, rings) = (segments.max(3), rings.max(2));
227 let columns = segments + 1;
228 let mut positions = Vec::with_capacity((columns * (rings + 1)) as usize);
229 let mut uvs = Vec::with_capacity(positions.capacity());
230 for ring in 0..=rings {
231 let v = ring as f32 / rings as f32;
232 let (sin_polar, cos_polar) = (v * PI).sin_cos();
233 for segment in 0..=segments {
234 let u = segment as f32 / segments as f32;
235 let (sin_around, cos_around) = ((u - 0.5) * 2.0 * PI).sin_cos();
236 positions.push([sin_polar * sin_around, -cos_polar, -sin_polar * cos_around]);
237 uvs.push([u, v]);
238 }
239 }
240 let indices = wrapped_grid_indices(segments, rings);
241 let normals = positions.clone();
242 Self::assembled(positions, uvs, normals, indices)
243 }
244
245 pub fn cylinder(segments: u32) -> Self {
261 let segments = segments.max(3);
262 let columns = segments + 1;
263 let mut positions = Vec::with_capacity((columns * 2) as usize);
264 let mut normals = Vec::with_capacity(positions.capacity());
265 let mut uvs = Vec::with_capacity(positions.capacity());
266 for v in [0.0, 1.0] {
267 for segment in 0..=segments {
268 let u = segment as f32 / segments as f32;
269 let (sin_around, cos_around) = ((u - 0.5) * 2.0 * PI).sin_cos();
270 positions.push([sin_around, v - 0.5, -cos_around]);
271 normals.push([sin_around, 0.0, -cos_around]);
272 uvs.push([u, v]);
273 }
274 }
275 let indices = wrapped_grid_indices(segments, 1);
276 Self::assembled(positions, uvs, normals, indices)
277 }
278
279 pub fn id(&self) -> u64 {
282 self.id
283 }
284
285 pub fn positions(&self) -> &[[f32; 3]] {
287 &self.positions
288 }
289
290 pub fn normals(&self) -> &[[f32; 3]] {
292 &self.normals
293 }
294
295 pub fn uvs(&self) -> &[[f32; 2]] {
297 &self.uvs
298 }
299
300 pub fn indices(&self) -> &[u32] {
302 &self.indices
303 }
304
305 pub fn cast(&self, origin: Vec3, direction: Vec3) -> Option<MeshHit> {
308 let mut nearest: Option<MeshHit> = None;
309 for triangle in 0..self.triangle_count() {
310 let [a, b, c] = self.corners(triangle);
311 let Some((distance, weights)) = ray_triangle(origin, direction, [a, b, c]) else {
312 continue;
313 };
314 if nearest.is_some_and(|hit| hit.distance <= distance) {
315 continue;
316 }
317 nearest = Some(MeshHit {
318 distance,
319 triangle,
320 uv: self.uv_at(triangle, weights),
321 });
322 }
323 nearest
324 }
325
326 pub fn cast_plane(&self, origin: Vec3, direction: Vec3, triangle: u32) -> Option<[f32; 2]> {
331 if triangle >= self.triangle_count() {
332 return None;
333 }
334 let [a, b, c] = self.corners(triangle);
335 let normal = (b - a).cross(c - a);
336 let along = normal.dot(direction);
337 if along.abs() <= f32::EPSILON * normal.length() * direction.length() {
338 return None;
339 }
340 let distance = normal.dot(a - origin) / along;
341 if distance <= 0.0 {
342 return None;
343 }
344 let point = origin + direction * distance;
345 let weights = barycentric(point, [a, b, c], normal)?;
346 Some(self.uv_at(triangle, weights))
347 }
348
349 pub fn point_at(&self, uv: [f32; 2]) -> Option<Vec3> {
352 const EDGE: f32 = 1.0e-4;
353 let point = Vec3::new(uv[0], uv[1], 0.0);
354 (0..self.triangle_count()).find_map(|triangle| {
355 let [ia, ib, ic] = self.triangle_indices(triangle);
356 let corner = |index: usize| {
357 let [u, v] = self.uvs[index];
358 Vec3::new(u, v, 0.0)
359 };
360 let flat = [corner(ia), corner(ib), corner(ic)];
361 let normal = (flat[1] - flat[0]).cross(flat[2] - flat[0]);
362 let [wa, wb, wc] = barycentric(point, flat, normal)?;
363 (wa >= -EDGE && wb >= -EDGE && wc >= -EDGE).then(|| {
364 let position = |index: usize| Vec3::from_array(self.positions[index]);
365 position(ia) * wa + position(ib) * wb + position(ic) * wc
366 })
367 })
368 }
369
370 pub fn nearest(&self, point: Vec3, transform: &Mat4) -> Option<MeshContact> {
373 let mut nearest: Option<MeshContact> = None;
374 for triangle in 0..self.triangle_count() {
375 let corners = self
376 .corners(triangle)
377 .map(|corner| transform.transform_point(corner));
378 let (at, weights) = nearest_on_triangle(point, corners);
379 let distance = (point - at).length();
380 if nearest.is_some_and(|known| known.distance <= distance) {
381 continue;
382 }
383 nearest = Some(MeshContact {
384 point: at,
385 distance,
386 uv: self.uv_at(triangle, weights),
387 });
388 }
389 nearest
390 }
391
392 pub fn bounds(&self) -> (Vec3, Vec3) {
395 *self.bounds.get_or_init(|| {
396 let mut low = Vec3::new(f32::INFINITY, f32::INFINITY, f32::INFINITY);
397 let mut high = -low;
398 for &position in &self.positions {
399 let point = Vec3::from_array(position);
400 (low, high) = (low.min(point), high.max(point));
401 }
402 (low, high)
403 })
404 }
405
406 pub fn bounds_in(&self, transform: &Mat4) -> (Vec3, Vec3) {
410 let (mesh_low, mesh_high) = self.bounds();
411 let mut low = Vec3::new(f32::INFINITY, f32::INFINITY, f32::INFINITY);
412 let mut high = -low;
413 for corner in 0..8 {
414 let pick = |bit: u32, low: f32, high: f32| if corner & bit == 0 { low } else { high };
415 let point = transform.transform_point(Vec3::new(
416 pick(1, mesh_low.x, mesh_high.x),
417 pick(2, mesh_low.y, mesh_high.y),
418 pick(4, mesh_low.z, mesh_high.z),
419 ));
420 (low, high) = (low.min(point), high.max(point));
421 }
422 (low, high)
423 }
424
425 pub fn texture_plane(&self) -> Option<TexturePlane> {
430 *self.texture_plane.get_or_init(|| {
431 self.flat_texture_plane()
432 .or_else(|| self.tangent_texture_plane())
433 })
434 }
435
436 fn flat_texture_plane(&self) -> Option<TexturePlane> {
437 let origin = self.point_at([0.0, 0.0])?;
438 let u_axis = self.point_at([1.0, 0.0])? - origin;
439 let v_axis = self.point_at([0.0, 1.0])? - origin;
440 let plane = TexturePlane {
441 origin,
442 u_axis,
443 v_axis,
444 };
445 let tolerance = 1.0e-3 * (u_axis.length() + v_axis.length());
446 let lies_flat = [[1.0, 1.0], [0.5, 0.5], [0.25, 0.75]].iter().all(|&uv| {
447 self.point_at(uv)
448 .is_some_and(|point| (point - plane.at(uv)).length() <= tolerance)
449 });
450 (lies_flat && u_axis.cross(v_axis).length() > tolerance * tolerance).then_some(plane)
451 }
452
453 fn tangent_texture_plane(&self) -> Option<TexturePlane> {
454 const STEP: f32 = 1.0 / 64.0;
455 let middle = self.point_at([0.5, 0.5])?;
456 let u_axis = (self.point_at([0.5 + STEP, 0.5])? - middle) * (1.0 / STEP);
457 let v_axis = (self.point_at([0.5, 0.5 + STEP])? - middle) * (1.0 / STEP);
458 (u_axis.cross(v_axis).length() > f32::EPSILON).then(|| TexturePlane {
459 origin: middle - u_axis * 0.5 - v_axis * 0.5,
460 u_axis,
461 v_axis,
462 })
463 }
464
465 fn triangle_count(&self) -> u32 {
466 (self.indices.len() / 3) as u32
467 }
468
469 fn triangle_indices(&self, triangle: u32) -> [usize; 3] {
470 let first = triangle as usize * 3;
471 [0, 1, 2].map(|corner| self.indices[first + corner] as usize)
472 }
473
474 fn corners(&self, triangle: u32) -> [Vec3; 3] {
475 self.triangle_indices(triangle)
476 .map(|index| Vec3::from_array(self.positions[index]))
477 }
478
479 fn uv_at(&self, triangle: u32, [wa, wb, wc]: [f32; 3]) -> [f32; 2] {
480 let [a, b, c] = self.triangle_indices(triangle).map(|index| self.uvs[index]);
481 [
482 a[0] * wa + b[0] * wb + c[0] * wc,
483 a[1] * wa + b[1] * wb + c[1] * wc,
484 ]
485 }
486
487 pub(super) fn assembled(
488 positions: Vec<[f32; 3]>,
489 uvs: Vec<[f32; 2]>,
490 normals: Vec<[f32; 3]>,
491 indices: Vec<u32>,
492 ) -> Self {
493 Self {
494 id: NEXT_MESH_ID.fetch_add(1, Ordering::Relaxed),
495 positions,
496 normals,
497 uvs,
498 indices,
499 texture_edges: TextureEdges::Seams,
500 texture_plane: OnceLock::new(),
501 bounds: OnceLock::new(),
502 }
503 }
504}
505
506impl TexturePlane {
507 pub fn at(&self, [u, v]: [f32; 2]) -> Vec3 {
509 self.origin + self.u_axis * u + self.v_axis * v
510 }
511}
512
513#[derive(Default)]
514struct MeshParts {
515 positions: Vec<[f32; 3]>,
516 normals: Vec<[f32; 3]>,
517 uvs: Vec<[f32; 2]>,
518 indices: Vec<u32>,
519}
520
521impl MeshParts {
522 fn quad(&mut self, top_left: Vec3, right: Vec3, down: Vec3) {
526 let base = self.positions.len() as u32;
527 let normal = down.cross(right).normalized().unwrap_or(Vec3::ZERO);
528 for (corner, uv) in [
529 (top_left, [0.0, 0.0]),
530 (top_left + right, [1.0, 0.0]),
531 (top_left + down, [0.0, 1.0]),
532 (top_left + right + down, [1.0, 1.0]),
533 ] {
534 self.positions.push(corner.to_array());
535 self.normals.push(normal.to_array());
536 self.uvs.push(uv);
537 }
538 self.indices
539 .extend([base, base + 1, base + 2, base + 2, base + 1, base + 3]);
540 }
541
542 fn into_mesh(self) -> Mesh {
543 Mesh::assembled(self.positions, self.uvs, self.normals, self.indices)
544 }
545}
546
547pub(super) fn smooth_normals(positions: &[[f32; 3]], indices: &[u32]) -> Vec<[f32; 3]> {
550 let mut sums = vec![Vec3::ZERO; positions.len()];
551 for triangle in indices.as_chunks::<3>().0 {
552 let corner = |index: u32| Vec3::from_array(positions[index as usize]);
553 let (a, b, c) = (
554 corner(triangle[0]),
555 corner(triangle[1]),
556 corner(triangle[2]),
557 );
558 let face = (b - a).cross(c - a);
559 for &index in triangle {
560 sums[index as usize] = sums[index as usize] + face;
561 }
562 }
563 sums.into_iter()
564 .map(|sum| {
565 sum.normalized()
566 .unwrap_or(Vec3::new(0.0, 0.0, -1.0))
567 .to_array()
568 })
569 .collect()
570}
571
572fn wrapped_grid_indices(segments: u32, rows: u32) -> Vec<u32> {
576 let columns = segments + 1;
577 let mut indices = Vec::with_capacity((segments * rows * 6) as usize);
578 for row in 0..rows {
579 for segment in 0..segments {
580 let top_left = row * columns + segment;
581 let bottom_left = top_left + columns;
582 indices.extend([
583 top_left,
584 top_left + 1,
585 bottom_left,
586 bottom_left,
587 top_left + 1,
588 bottom_left + 1,
589 ]);
590 }
591 }
592 indices
593}
594
595fn ray_triangle(origin: Vec3, direction: Vec3, [a, b, c]: [Vec3; 3]) -> Option<(f32, [f32; 3])> {
598 let (edge_b, edge_c) = (b - a, c - a);
599 let p = direction.cross(edge_c);
600 let determinant = edge_b.dot(p);
601 if determinant.abs() <= f32::EPSILON * edge_b.length() * edge_c.length() * direction.length() {
602 return None;
603 }
604 let inverse = 1.0 / determinant;
605 let offset = origin - a;
606 let wb = offset.dot(p) * inverse;
607 if !(0.0..=1.0).contains(&wb) {
608 return None;
609 }
610 let q = offset.cross(edge_b);
611 let wc = direction.dot(q) * inverse;
612 if wc < 0.0 || wb + wc > 1.0 {
613 return None;
614 }
615 let distance = edge_c.dot(q) * inverse;
616 (distance > 0.0).then_some((distance, [1.0 - wb - wc, wb, wc]))
617}
618
619fn nearest_on_triangle(point: Vec3, [a, b, c]: [Vec3; 3]) -> (Vec3, [f32; 3]) {
623 let (ab, ac) = (b - a, c - a);
624 let (d1, d2) = (ab.dot(point - a), ac.dot(point - a));
625 if d1 <= 0.0 && d2 <= 0.0 {
626 return (a, [1.0, 0.0, 0.0]);
627 }
628 let (d3, d4) = (ab.dot(point - b), ac.dot(point - b));
629 if d3 >= 0.0 && d4 <= d3 {
630 return (b, [0.0, 1.0, 0.0]);
631 }
632 let vc = d1 * d4 - d3 * d2;
633 if vc <= 0.0 && d1 >= 0.0 && d3 <= 0.0 {
634 let v = d1 / (d1 - d3);
635 return (a + ab * v, [1.0 - v, v, 0.0]);
636 }
637 let (d5, d6) = (ab.dot(point - c), ac.dot(point - c));
638 if d6 >= 0.0 && d5 <= d6 {
639 return (c, [0.0, 0.0, 1.0]);
640 }
641 let vb = d5 * d2 - d1 * d6;
642 if vb <= 0.0 && d2 >= 0.0 && d6 <= 0.0 {
643 let w = d2 / (d2 - d6);
644 return (a + ac * w, [1.0 - w, 0.0, w]);
645 }
646 let va = d3 * d6 - d5 * d4;
647 if va <= 0.0 && d4 - d3 >= 0.0 && d5 - d6 >= 0.0 {
648 let w = (d4 - d3) / ((d4 - d3) + (d5 - d6));
649 return (b + (c - b) * w, [0.0, 1.0 - w, w]);
650 }
651 let total = va + vb + vc;
652 if !total.is_normal() {
653 return (a, [1.0, 0.0, 0.0]);
654 }
655 let (v, w) = (vb / total, vc / total);
656 (a + ab * v + ac * w, [1.0 - v - w, v, w])
657}
658
659fn barycentric(point: Vec3, [a, b, c]: [Vec3; 3], normal: Vec3) -> Option<[f32; 3]> {
662 let area = normal.dot(normal);
663 if !area.is_normal() {
664 return None;
665 }
666 let wb = normal.dot((point - a).cross(c - a)) / area;
667 let wc = normal.dot((b - a).cross(point - a)) / area;
668 Some([1.0 - wb - wc, wb, wc])
669}