1use std::{collections::BTreeSet, error::Error, fmt, sync::Arc};
2
3use crate::{Color, LogicalPixels, Vec3};
4
5const MAX_LOGICAL_EDGE_METRIC: f32 = 1_048_576.0;
6
7#[derive(Debug, Clone, Copy, PartialEq)]
13pub struct SurfaceStyle3d {
14 color: Color,
15}
16
17impl SurfaceStyle3d {
18 pub fn opaque(color: Color) -> Result<Self, Mesh3dStyleError> {
20 if !color.is_normalized() || color.alpha() != 1.0 {
21 return Err(Mesh3dStyleError::InvalidSurfaceColor);
22 }
23 Ok(Self { color })
24 }
25
26 pub const fn color(self) -> Color {
28 self.color
29 }
30}
31
32#[derive(Debug, Clone, Copy, PartialEq)]
38pub struct MeshStyle3d {
39 surface: Option<SurfaceStyle3d>,
40 wireframe: Option<WireframeStyle3d>,
41}
42
43impl MeshStyle3d {
44 pub const fn surface(surface: SurfaceStyle3d) -> Self {
46 Self {
47 surface: Some(surface),
48 wireframe: None,
49 }
50 }
51
52 pub const fn wireframe(wireframe: WireframeStyle3d) -> Self {
54 Self {
55 surface: None,
56 wireframe: Some(wireframe),
57 }
58 }
59
60 pub const fn with_wireframe(mut self, wireframe: WireframeStyle3d) -> Self {
62 self.wireframe = Some(wireframe);
63 self
64 }
65
66 pub const fn surface_style(self) -> Option<SurfaceStyle3d> {
68 self.surface
69 }
70
71 pub const fn wireframe_style(self) -> Option<WireframeStyle3d> {
73 self.wireframe
74 }
75}
76
77#[derive(Debug, Clone, Copy, PartialEq)]
87pub struct WireframeStyle3d {
88 visible_color: Color,
89 visible_width: LogicalPixels,
90 hidden: Option<HiddenEdgeStyle3d>,
91}
92
93#[derive(Debug, Clone, Copy, PartialEq)]
94struct HiddenEdgeStyle3d {
95 color: Color,
96 width: LogicalPixels,
97 dash_length: LogicalPixels,
98 gap_length: LogicalPixels,
99}
100
101impl WireframeStyle3d {
102 pub fn visible(color: Color, width: LogicalPixels) -> Result<Self, Mesh3dStyleError> {
104 validate_edge_color_width(color, width)?;
105 Ok(Self {
106 visible_color: color,
107 visible_width: width,
108 hidden: None,
109 })
110 }
111
112 pub fn with_hidden(
117 mut self,
118 color: Color,
119 width: LogicalPixels,
120 dash_length: LogicalPixels,
121 gap_length: LogicalPixels,
122 ) -> Result<Self, Mesh3dStyleError> {
123 validate_edge_color_width(color, width)?;
124 if dash_length.get() > MAX_LOGICAL_EDGE_METRIC
125 || gap_length.get() > MAX_LOGICAL_EDGE_METRIC
126 || !(dash_length.get() + gap_length.get()).is_finite()
127 {
128 return Err(Mesh3dStyleError::InvalidDashPattern);
129 }
130 self.hidden = Some(HiddenEdgeStyle3d {
131 color,
132 width,
133 dash_length,
134 gap_length,
135 });
136 Ok(self)
137 }
138
139 pub const fn visible_color(self) -> Color {
141 self.visible_color
142 }
143
144 pub const fn visible_width(self) -> LogicalPixels {
146 self.visible_width
147 }
148
149 pub const fn hidden_enabled(self) -> bool {
151 self.hidden.is_some()
152 }
153
154 pub const fn hidden_color(self) -> Option<Color> {
156 match self.hidden {
157 Some(hidden) => Some(hidden.color),
158 None => None,
159 }
160 }
161
162 pub const fn hidden_width(self) -> Option<LogicalPixels> {
164 match self.hidden {
165 Some(hidden) => Some(hidden.width),
166 None => None,
167 }
168 }
169
170 pub const fn hidden_pattern(self) -> Option<(LogicalPixels, LogicalPixels)> {
172 match self.hidden {
173 Some(hidden) => Some((hidden.dash_length, hidden.gap_length)),
174 None => None,
175 }
176 }
177}
178
179#[derive(Debug, Clone, Copy, PartialEq, Eq)]
181pub enum Mesh3dStyleError {
182 InvalidSurfaceColor,
184 InvalidColorOrWidth,
186 InvalidDashPattern,
188}
189
190impl fmt::Display for Mesh3dStyleError {
191 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
192 match self {
193 Self::InvalidSurfaceColor => write!(formatter, "3D surface color must be opaque"),
194 Self::InvalidColorOrWidth => {
195 write!(formatter, "3D edge color must be opaque and width positive")
196 }
197 Self::InvalidDashPattern => {
198 write!(formatter, "3D hidden-edge dash and gap must be positive")
199 }
200 }
201 }
202}
203
204impl Error for Mesh3dStyleError {}
205
206fn validate_edge_color_width(color: Color, width: LogicalPixels) -> Result<(), Mesh3dStyleError> {
207 if color.is_normalized() && color.alpha() == 1.0 && width.get() <= MAX_LOGICAL_EDGE_METRIC {
208 Ok(())
209 } else {
210 Err(Mesh3dStyleError::InvalidColorOrWidth)
211 }
212}
213
214#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
219pub struct MeshEdge3d {
220 start: u32,
221 end: u32,
222}
223
224impl MeshEdge3d {
225 pub fn new(start: u32, end: u32) -> Result<Self, Mesh3dError> {
227 if start == end {
228 return Err(Mesh3dError::DegenerateDisplayEdge { start, end });
229 }
230 Ok(Self { start, end })
231 }
232
233 pub const fn start(self) -> u32 {
235 self.start
236 }
237
238 pub const fn end(self) -> u32 {
240 self.end
241 }
242
243 fn canonical(self) -> (u32, u32) {
244 if self.start < self.end {
245 (self.start, self.end)
246 } else {
247 (self.end, self.start)
248 }
249 }
250}
251
252#[derive(Debug, Clone, PartialEq)]
263pub struct Mesh3d {
264 vertices: Arc<[Vec3]>,
265 triangle_indices: Arc<[u32]>,
266 display_edges: Arc<[MeshEdge3d]>,
267 bounds_min: Vec3,
268 bounds_max: Vec3,
269}
270
271impl Mesh3d {
272 pub fn new(vertices: Vec<Vec3>, triangle_indices: Vec<u32>) -> Result<Self, Mesh3dError> {
274 Self::with_display_edges(vertices, triangle_indices, Vec::new())
275 }
276
277 pub fn with_display_edges(
285 vertices: Vec<Vec3>,
286 triangle_indices: Vec<u32>,
287 display_edges: Vec<MeshEdge3d>,
288 ) -> Result<Self, Mesh3dError> {
289 if vertices.is_empty() {
290 return Err(Mesh3dError::EmptyVertices);
291 }
292 if triangle_indices.is_empty() && display_edges.is_empty() {
293 return Err(Mesh3dError::EmptyGeometry);
294 }
295 if !triangle_indices.len().is_multiple_of(3) {
296 return Err(Mesh3dError::InvalidTriangleIndexCount {
297 index_count: triangle_indices.len(),
298 });
299 }
300
301 for (triangle, indices) in triangle_indices.chunks_exact(3).enumerate() {
302 let [first, second, third] = [indices[0], indices[1], indices[2]];
303 validate_index(first, vertices.len())?;
304 validate_index(second, vertices.len())?;
305 validate_index(third, vertices.len())?;
306 if first == second
307 || second == third
308 || first == third
309 || triangle_is_degenerate(
310 vertices[first as usize],
311 vertices[second as usize],
312 vertices[third as usize],
313 )
314 {
315 return Err(Mesh3dError::DegenerateTriangle { triangle });
316 }
317 }
318
319 let mut unique_edges = BTreeSet::new();
320 for edge in &display_edges {
321 validate_index(edge.start, vertices.len())?;
322 validate_index(edge.end, vertices.len())?;
323 if vertices[edge.start as usize] == vertices[edge.end as usize] {
324 return Err(Mesh3dError::DegenerateDisplayEdge {
325 start: edge.start,
326 end: edge.end,
327 });
328 }
329 if !unique_edges.insert(edge.canonical()) {
330 return Err(Mesh3dError::DuplicateDisplayEdge {
331 start: edge.start,
332 end: edge.end,
333 });
334 }
335 }
336
337 let (bounds_min, bounds_max) = mesh_bounds(&vertices);
338 Ok(Self {
339 vertices: vertices.into(),
340 triangle_indices: triangle_indices.into(),
341 display_edges: display_edges.into(),
342 bounds_min,
343 bounds_max,
344 })
345 }
346
347 pub fn vertices(&self) -> &[Vec3] {
349 &self.vertices
350 }
351
352 pub fn triangle_indices(&self) -> &[u32] {
354 &self.triangle_indices
355 }
356
357 pub fn display_edges(&self) -> &[MeshEdge3d] {
359 &self.display_edges
360 }
361
362 pub fn triangle_count(&self) -> usize {
364 self.triangle_indices.len() / 3
365 }
366
367 pub const fn bounds_min(&self) -> Vec3 {
369 self.bounds_min
370 }
371
372 pub const fn bounds_max(&self) -> Vec3 {
374 self.bounds_max
375 }
376
377 pub fn recovery_memory_bytes(&self) -> usize {
379 self.vertices
380 .len()
381 .saturating_mul(std::mem::size_of::<Vec3>())
382 .saturating_add(
383 self.triangle_indices
384 .len()
385 .saturating_mul(std::mem::size_of::<u32>()),
386 )
387 .saturating_add(
388 self.display_edges
389 .len()
390 .saturating_mul(std::mem::size_of::<MeshEdge3d>()),
391 )
392 }
393}
394
395#[derive(Debug, Clone, Copy, PartialEq, Eq)]
397pub enum Mesh3dError {
398 EmptyVertices,
400 EmptyGeometry,
402 InvalidTriangleIndexCount {
404 index_count: usize,
406 },
407 IndexOutOfBounds {
409 index: u32,
411 vertex_count: usize,
413 },
414 DegenerateTriangle {
416 triangle: usize,
418 },
419 DegenerateDisplayEdge {
421 start: u32,
423 end: u32,
425 },
426 DuplicateDisplayEdge {
428 start: u32,
430 end: u32,
432 },
433}
434
435impl fmt::Display for Mesh3dError {
436 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
437 match self {
438 Self::EmptyVertices => write!(formatter, "3D mesh requires at least one vertex"),
439 Self::EmptyGeometry => {
440 write!(formatter, "3D mesh requires triangles or display edges")
441 }
442 Self::InvalidTriangleIndexCount { index_count } => write!(
443 formatter,
444 "3D mesh triangle index count must be non-zero and divisible by three, got {index_count}"
445 ),
446 Self::IndexOutOfBounds {
447 index,
448 vertex_count,
449 } => write!(
450 formatter,
451 "3D mesh index {index} is outside {vertex_count} vertices"
452 ),
453 Self::DegenerateTriangle { triangle } => {
454 write!(formatter, "3D mesh triangle {triangle} has zero area")
455 }
456 Self::DegenerateDisplayEdge { start, end } => {
457 write!(formatter, "3D display edge {start}-{end} has zero length")
458 }
459 Self::DuplicateDisplayEdge { start, end } => {
460 write!(formatter, "3D display edge {start}-{end} is duplicated")
461 }
462 }
463 }
464}
465
466impl Error for Mesh3dError {}
467
468fn validate_index(index: u32, vertex_count: usize) -> Result<(), Mesh3dError> {
469 ((index as u64) < vertex_count as u64)
470 .then_some(())
471 .ok_or(Mesh3dError::IndexOutOfBounds {
472 index,
473 vertex_count,
474 })
475}
476
477fn triangle_is_degenerate(first: Vec3, second: Vec3, third: Vec3) -> bool {
478 let ab = (
479 second.x() as f64 - first.x() as f64,
480 second.y() as f64 - first.y() as f64,
481 second.z() as f64 - first.z() as f64,
482 );
483 let ac = (
484 third.x() as f64 - first.x() as f64,
485 third.y() as f64 - first.y() as f64,
486 third.z() as f64 - first.z() as f64,
487 );
488 let cross = (
489 ab.1 * ac.2 - ab.2 * ac.1,
490 ab.2 * ac.0 - ab.0 * ac.2,
491 ab.0 * ac.1 - ab.1 * ac.0,
492 );
493 cross.0 == 0.0 && cross.1 == 0.0 && cross.2 == 0.0
494}
495
496fn mesh_bounds(vertices: &[Vec3]) -> (Vec3, Vec3) {
497 let first = vertices[0];
498 let mut minimum = [first.x(), first.y(), first.z()];
499 let mut maximum = minimum;
500 for vertex in &vertices[1..] {
501 let components = [vertex.x(), vertex.y(), vertex.z()];
502 for axis in 0..3 {
503 minimum[axis] = minimum[axis].min(components[axis]);
504 maximum[axis] = maximum[axis].max(components[axis]);
505 }
506 }
507 (
508 Vec3::new_unchecked(minimum[0], minimum[1], minimum[2]),
509 Vec3::new_unchecked(maximum[0], maximum[1], maximum[2]),
510 )
511}
512
513#[cfg(test)]
514mod tests {
515 use super::{
516 Mesh3d, Mesh3dError, Mesh3dStyleError, MeshEdge3d, MeshStyle3d, SurfaceStyle3d,
517 WireframeStyle3d,
518 };
519 use crate::{Color, LogicalPixels, UnitError, Vec3};
520
521 fn vector(x: f32, y: f32, z: f32) -> Vec3 {
522 Vec3::new(x, y, z).unwrap()
523 }
524
525 fn logical(value: f32) -> LogicalPixels {
526 LogicalPixels::new(value).unwrap()
527 }
528
529 #[test]
530 fn mesh_validates_topology_and_preserves_explicit_edges() {
531 let mesh = Mesh3d::with_display_edges(
532 vec![
533 vector(-1.0, -1.0, 0.0),
534 vector(1.0, -1.0, 0.0),
535 vector(0.0, 1.0, 0.0),
536 ],
537 vec![0, 1, 2],
538 vec![
539 MeshEdge3d::new(0, 1).unwrap(),
540 MeshEdge3d::new(1, 2).unwrap(),
541 ],
542 )
543 .unwrap();
544 assert_eq!(mesh.triangle_count(), 1);
545 assert_eq!(mesh.display_edges().len(), 2);
546 assert_eq!(mesh.bounds_min(), vector(-1.0, -1.0, 0.0));
547 assert_eq!(mesh.bounds_max(), vector(1.0, 1.0, 0.0));
548 }
549
550 #[test]
551 fn mesh_rejects_invalid_and_degenerate_topology() {
552 assert_eq!(
553 Mesh3d::new(Vec::new(), vec![0, 1, 2]),
554 Err(Mesh3dError::EmptyVertices)
555 );
556 let vertices = vec![
557 vector(0.0, 0.0, 0.0),
558 vector(1.0, 0.0, 0.0),
559 vector(2.0, 0.0, 0.0),
560 ];
561 assert_eq!(
562 Mesh3d::new(vertices.clone(), vec![0, 1]),
563 Err(Mesh3dError::InvalidTriangleIndexCount { index_count: 2 })
564 );
565 assert_eq!(
566 Mesh3d::new(vertices.clone(), vec![0, 1, 3]),
567 Err(Mesh3dError::IndexOutOfBounds {
568 index: 3,
569 vertex_count: 3,
570 })
571 );
572 assert_eq!(
573 Mesh3d::new(vertices, vec![0, 1, 2]),
574 Err(Mesh3dError::DegenerateTriangle { triangle: 0 })
575 );
576 }
577
578 #[test]
579 fn mesh_rejects_duplicate_undirected_display_edges() {
580 let vertices = vec![
581 vector(0.0, 0.0, 0.0),
582 vector(1.0, 0.0, 0.0),
583 vector(0.0, 1.0, 0.0),
584 ];
585 assert_eq!(
586 Mesh3d::with_display_edges(
587 vertices,
588 vec![0, 1, 2],
589 vec![
590 MeshEdge3d::new(0, 1).unwrap(),
591 MeshEdge3d::new(1, 0).unwrap(),
592 ],
593 ),
594 Err(Mesh3dError::DuplicateDisplayEdge { start: 1, end: 0 })
595 );
596 assert_eq!(
597 MeshEdge3d::new(2, 2),
598 Err(Mesh3dError::DegenerateDisplayEdge { start: 2, end: 2 })
599 );
600 }
601
602 #[test]
603 fn mesh_rejects_geometrically_zero_length_display_edges() {
604 assert_eq!(
605 Mesh3d::with_display_edges(
606 vec![vector(1.0, 2.0, 3.0), vector(1.0, 2.0, 3.0)],
607 Vec::new(),
608 vec![MeshEdge3d::new(0, 1).unwrap()],
609 ),
610 Err(Mesh3dError::DegenerateDisplayEdge { start: 0, end: 1 })
611 );
612 }
613
614 #[test]
615 fn mesh_accepts_edge_only_construction_geometry() {
616 let mesh = Mesh3d::with_display_edges(
617 vec![vector(0.0, 0.0, 0.0), vector(1.0, 0.0, 0.0)],
618 Vec::new(),
619 vec![MeshEdge3d::new(0, 1).unwrap()],
620 )
621 .unwrap();
622 assert_eq!(mesh.triangle_count(), 0);
623 assert_eq!(mesh.display_edges().len(), 1);
624 assert_eq!(
625 Mesh3d::new(vec![vector(0.0, 0.0, 0.0)], Vec::new()),
626 Err(Mesh3dError::EmptyGeometry)
627 );
628 }
629
630 #[test]
631 fn wireframe_style_validates_logical_pixel_contract() {
632 let style = WireframeStyle3d::visible(Color::WHITE, logical(2.0))
633 .unwrap()
634 .with_hidden(
635 Color::rgba(0.5, 0.5, 0.5, 1.0),
636 logical(1.5),
637 logical(6.0),
638 logical(4.0),
639 )
640 .unwrap();
641 assert_eq!(style.visible_width(), logical(2.0));
642 assert_eq!(style.hidden_pattern(), Some((logical(6.0), logical(4.0))));
643 assert_eq!(
644 LogicalPixels::new(0.0),
645 Err(UnitError::InvalidLogicalPixels { value: 0.0 })
646 );
647 assert_eq!(
648 WireframeStyle3d::visible(Color::WHITE, logical(f32::MAX)),
649 Err(Mesh3dStyleError::InvalidColorOrWidth)
650 );
651 assert_eq!(
652 WireframeStyle3d::visible(Color::rgb(-0.01, 0.0, 0.0), logical(1.0)),
653 Err(Mesh3dStyleError::InvalidColorOrWidth)
654 );
655 assert_eq!(
656 WireframeStyle3d::visible(Color::WHITE, logical(1.0))
657 .unwrap()
658 .with_hidden(Color::WHITE, logical(1.0), logical(f32::MAX), logical(2.0),),
659 Err(Mesh3dStyleError::InvalidDashPattern)
660 );
661 assert_eq!(
662 WireframeStyle3d::visible(Color::WHITE, logical(1.0))
663 .unwrap()
664 .with_hidden(
665 Color::WHITE,
666 logical(1.0),
667 logical(f32::MAX),
668 logical(f32::MAX),
669 ),
670 Err(Mesh3dStyleError::InvalidDashPattern)
671 );
672 }
673
674 #[test]
675 fn mesh_style_keeps_surface_and_wireframe_extensible() {
676 let surface = SurfaceStyle3d::opaque(Color::rgb(0.2, 0.3, 0.4)).unwrap();
677 let wireframe = WireframeStyle3d::visible(Color::WHITE, logical(2.0)).unwrap();
678 let style = MeshStyle3d::surface(surface).with_wireframe(wireframe);
679 assert_eq!(style.surface_style(), Some(surface));
680 assert_eq!(style.wireframe_style(), Some(wireframe));
681 assert_eq!(
682 SurfaceStyle3d::opaque(Color::rgba(1.0, 1.0, 1.0, 0.5)),
683 Err(Mesh3dStyleError::InvalidSurfaceColor)
684 );
685 assert_eq!(
686 SurfaceStyle3d::opaque(Color::rgb(1.01, 0.0, 0.0)),
687 Err(Mesh3dStyleError::InvalidSurfaceColor)
688 );
689 assert_eq!(MeshStyle3d::wireframe(wireframe).surface_style(), None);
690 }
691}