Skip to main content

sim_engine/
mesh3d.rs

1use std::{error::Error, fmt, sync::Arc};
2
3use crate::{Color, LogicalPixels, Vec3};
4
5const MAX_LOGICAL_EDGE_METRIC: f32 = 1_048_576.0;
6
7#[path = "mesh3d_uv.rs"]
8mod uv;
9pub use uv::{TextureAddressMode3d, TextureUvTransform3d, TextureUvTransformError};
10
11#[path = "mesh3d_material.rs"]
12mod material;
13pub use material::{SurfaceAlphaMode3d, SurfaceSidedness3d, SurfaceStyle3d};
14#[path = "mesh3d_environment.rs"]
15mod environment;
16pub use environment::{
17    AmbientLight3d, DirectionalLight3d, Fog3d, Fog3dError, Lighting3d, Lighting3dError,
18    SurfaceLighting3d,
19};
20
21/// Extensible visual material bundle for a retained 3D object.
22///
23/// Surface and wireframe presentation are independent. Edge-only construction
24/// geometry uses `surface = None`; future section materials can extend
25/// [`SurfaceStyle3d`] without changing scene insertion or object addressing.
26#[derive(Debug, Clone, Copy, PartialEq)]
27pub struct MeshStyle3d {
28    surface: Option<SurfaceStyle3d>,
29    wireframe: Option<WireframeStyle3d>,
30}
31
32impl MeshStyle3d {
33    /// Creates an object with the selected surface material and no display edges.
34    pub const fn surface(surface: SurfaceStyle3d) -> Self {
35        Self {
36            surface: Some(surface),
37            wireframe: None,
38        }
39    }
40
41    /// Creates display edges without a surface/depth-writing face pass.
42    pub const fn wireframe(wireframe: WireframeStyle3d) -> Self {
43        Self {
44            surface: None,
45            wireframe: Some(wireframe),
46        }
47    }
48
49    /// Adds or replaces display-edge presentation.
50    pub const fn with_wireframe(mut self, wireframe: WireframeStyle3d) -> Self {
51        self.wireframe = Some(wireframe);
52        self
53    }
54
55    /// Returns the optional surface material.
56    pub const fn surface_style(self) -> Option<SurfaceStyle3d> {
57        self.surface
58    }
59
60    /// Returns the optional edge presentation.
61    pub const fn wireframe_style(self) -> Option<WireframeStyle3d> {
62        self.wireframe
63    }
64}
65
66/// Logical-screen presentation for explicit mathematical mesh edges.
67///
68/// Visible fragments are solid. Fragments occluded beyond the depth buffer's
69/// conservative coplanar tolerance may be drawn with a logical-pixel dash/gap
70/// pattern. Classification uses one implementation depth unit away from the
71/// camera for hidden fragments and one unit toward it for visible fragments,
72/// with visible fragments rendered last. Therefore coplanar and
73/// sub-depth-resolution separations intentionally resolve as visible; this is
74/// raster visibility, not exact analytic solid geometry.
75#[derive(Debug, Clone, Copy, PartialEq)]
76pub struct WireframeStyle3d {
77    visible_color: Color,
78    visible_width: LogicalPixels,
79    hidden: Option<HiddenEdgeStyle3d>,
80}
81
82#[derive(Debug, Clone, Copy, PartialEq)]
83struct HiddenEdgeStyle3d {
84    color: Color,
85    width: LogicalPixels,
86    dash_length: LogicalPixels,
87    gap_length: LogicalPixels,
88}
89
90impl WireframeStyle3d {
91    /// Largest accepted width, dash, or gap in logical pixels.
92    ///
93    /// The bound keeps every style-derived shader operation inside the
94    /// cross-backend arithmetic envelope.
95    pub const MAX_LOGICAL_PIXELS: f32 = MAX_LOGICAL_EDGE_METRIC;
96
97    /// Creates solid visible edges with hidden fragments disabled.
98    pub fn visible(color: Color, width: LogicalPixels) -> Result<Self, Mesh3dStyleError> {
99        validate_edge_color_width(color, width)?;
100        Ok(Self {
101            visible_color: color,
102            visible_width: width,
103            hidden: None,
104        })
105    }
106
107    /// Enables dashed depth-occluded fragments in logical screen pixels.
108    ///
109    /// Occlusion must exceed the conservative two-unit coplanar tolerance
110    /// documented on [`WireframeStyle3d`] before a fragment resolves hidden.
111    pub fn with_hidden(
112        mut self,
113        color: Color,
114        width: LogicalPixels,
115        dash_length: LogicalPixels,
116        gap_length: LogicalPixels,
117    ) -> Result<Self, Mesh3dStyleError> {
118        validate_edge_color_width(color, width)?;
119        if !is_stable_edge_metric(dash_length.get())
120            || !is_stable_edge_metric(gap_length.get())
121            || !(dash_length.get() + gap_length.get()).is_finite()
122        {
123            return Err(Mesh3dStyleError::InvalidDashPattern);
124        }
125        self.hidden = Some(HiddenEdgeStyle3d {
126            color,
127            width,
128            dash_length,
129            gap_length,
130        });
131        Ok(self)
132    }
133
134    /// Returns the solid visible-edge color in linear RGBA.
135    pub const fn visible_color(self) -> Color {
136        self.visible_color
137    }
138
139    /// Returns visible-edge width in logical screen pixels.
140    pub const fn visible_width(self) -> LogicalPixels {
141        self.visible_width
142    }
143
144    /// Returns whether depth-occluded edge fragments should be drawn.
145    pub const fn hidden_enabled(self) -> bool {
146        self.hidden.is_some()
147    }
148
149    /// Returns hidden-edge color when enabled.
150    pub const fn hidden_color(self) -> Option<Color> {
151        match self.hidden {
152            Some(hidden) => Some(hidden.color),
153            None => None,
154        }
155    }
156
157    /// Returns hidden-edge width in logical screen pixels when enabled.
158    pub const fn hidden_width(self) -> Option<LogicalPixels> {
159        match self.hidden {
160            Some(hidden) => Some(hidden.width),
161            None => None,
162        }
163    }
164
165    /// Returns hidden dash and gap lengths in logical screen pixels.
166    pub const fn hidden_pattern(self) -> Option<(LogicalPixels, LogicalPixels)> {
167        match self.hidden {
168            Some(hidden) => Some((hidden.dash_length, hidden.gap_length)),
169            None => None,
170        }
171    }
172}
173
174/// Rejection reason for logical-screen 3D edge presentation.
175#[derive(Debug, Clone, Copy, PartialEq, Eq)]
176pub enum Mesh3dStyleError {
177    /// A mask/blend tint must have finite straight-linear RGBA in 0..=1.
178    InvalidMaterialColor,
179    /// The alpha-mask cutoff must be zero or normal and finite in 0..=1.
180    InvalidMaskCutoff,
181    /// The legacy opaque constructor requires normalized color with alpha one.
182    InvalidSurfaceColor,
183    /// Edge color must be normalized and opaque, and width must be a normal
184    /// positive value no greater than [`WireframeStyle3d::MAX_LOGICAL_PIXELS`].
185    InvalidColorOrWidth,
186    /// Hidden dash and gap must be normal positive values, each no greater than
187    /// [`WireframeStyle3d::MAX_LOGICAL_PIXELS`], with a finite sum.
188    InvalidDashPattern,
189}
190
191impl fmt::Display for Mesh3dStyleError {
192    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
193        match self {
194            Self::InvalidMaterialColor => write!(
195                formatter,
196                "3D material color must be normalized straight-linear RGBA"
197            ),
198            Self::InvalidMaskCutoff => write!(
199                formatter,
200                "3D mask cutoff must be zero or normal and finite in 0..=1"
201            ),
202            Self::InvalidSurfaceColor => write!(formatter, "3D surface color must be opaque"),
203            Self::InvalidColorOrWidth => {
204                write!(
205                    formatter,
206                    "3D edge color must be opaque and width must be normal and in 0..={MAX_LOGICAL_EDGE_METRIC} logical pixels"
207                )
208            }
209            Self::InvalidDashPattern => {
210                write!(
211                    formatter,
212                    "3D hidden-edge dash and gap must each be normal and in 0..={MAX_LOGICAL_EDGE_METRIC} logical pixels with a finite sum"
213                )
214            }
215        }
216    }
217}
218
219impl Error for Mesh3dStyleError {}
220
221fn validate_edge_color_width(color: Color, width: LogicalPixels) -> Result<(), Mesh3dStyleError> {
222    if color.is_normalized() && color.alpha() == 1.0 && is_stable_edge_metric(width.get()) {
223        Ok(())
224    } else {
225        Err(Mesh3dStyleError::InvalidColorOrWidth)
226    }
227}
228
229fn is_stable_edge_metric(value: f32) -> bool {
230    value.is_normal() && value <= MAX_LOGICAL_EDGE_METRIC
231}
232
233/// One explicit display edge in a retained 3D mesh.
234///
235/// Endpoints index the mesh vertex array. A mesh validates the indices and
236/// rejects repeated or zero-length edges when it is constructed.
237#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
238pub struct MeshEdge3d {
239    start: u32,
240    end: u32,
241}
242
243impl MeshEdge3d {
244    /// Describes an edge between two distinct vertex indices.
245    pub fn new(start: u32, end: u32) -> Result<Self, Mesh3dError> {
246        if start == end {
247            return Err(Mesh3dError::DegenerateDisplayEdge { start, end });
248        }
249        Ok(Self { start, end })
250    }
251
252    /// Returns the first mesh vertex index.
253    pub const fn start(self) -> u32 {
254        self.start
255    }
256
257    /// Returns the second mesh vertex index.
258    pub const fn end(self) -> u32 {
259        self.end
260    }
261
262    fn canonical(self) -> (u32, u32) {
263        if self.start < self.end {
264            (self.start, self.end)
265        } else {
266            (self.end, self.start)
267        }
268    }
269}
270
271#[derive(Debug, PartialEq)]
272struct Mesh3dStorage {
273    vertices: Vec<Vec3>,
274    triangle_indices: Vec<u32>,
275    display_edges: Vec<MeshEdge3d>,
276    texture_coordinates: Vec<TextureCoordinate2d>,
277    vertex_colors: Vec<Color>,
278    normals: Vec<Vec3>,
279}
280
281#[path = "mesh3d_attributes.rs"]
282mod attributes;
283pub use attributes::Mesh3dAttributes;
284
285/// Normalized texture coordinate with a top-left origin and downward V axis.
286///
287/// Both components are finite in `0..=1`. The textured 3D path uses mip level
288/// zero and clamp-to-edge addressing. Atlas cells should map geometry to their
289/// edge texel centers for nearest sampling. Strict linear-filter isolation also
290/// requires host-owned extruded gutters to tolerate interpolation rounding.
291#[derive(Debug, Clone, Copy, PartialEq)]
292pub struct TextureCoordinate2d {
293    u: f32,
294    v: f32,
295}
296
297impl TextureCoordinate2d {
298    /// Validates normalized U/V without clamping invalid caller input.
299    pub fn new(u: f32, v: f32) -> Result<Self, Mesh3dError> {
300        if !u.is_finite()
301            || !v.is_finite()
302            || !(0.0..=1.0).contains(&u)
303            || !(0.0..=1.0).contains(&v)
304        {
305            return Err(Mesh3dError::InvalidTextureCoordinate);
306        }
307        Ok(Self { u, v })
308    }
309    /// Horizontal normalized texture coordinate, increasing toward the right.
310    pub const fn u(self) -> f32 {
311        self.u
312    }
313    /// Vertical normalized texture coordinate, increasing toward the bottom.
314    pub const fn v(self) -> f32 {
315        self.v
316    }
317}
318
319/// Immutable validated topology for retained stereometry rendering.
320///
321/// Vertices use caller-defined model-space world units. Triangle indices are a
322/// flat triangle list. Winding is preserved but deliberately not interpreted:
323/// the current surface pass disables face culling, and a global
324/// "counter-clockwise" rule is meaningless without a declared outward side.
325/// Optional display edges identify the mathematical edges that a later
326/// visible/hidden-line pass should draw; they are not inferred from triangle
327/// adjacency because triangulation diagonals are not necessarily meaningful
328/// construction edges. A mesh may contain surfaces, display edges, or both.
329#[derive(Debug, Clone, PartialEq)]
330pub struct Mesh3d {
331    storage: Arc<Mesh3dStorage>,
332    bounds_min: Vec3,
333    bounds_max: Vec3,
334}
335
336impl Mesh3d {
337    /// Builds a surface mesh without explicit display edges.
338    pub fn new(vertices: Vec<Vec3>, triangle_indices: Vec<u32>) -> Result<Self, Mesh3dError> {
339        Self::with_display_edges(vertices, triangle_indices, Vec::new())
340    }
341
342    /// Builds a mesh with explicit mathematical display edges.
343    ///
344    /// Construction rejects an empty vertex set, geometry with neither
345    /// triangles nor display edges, incomplete triangle lists, out-of-range
346    /// indices, repeated/collinear triangle vertices, duplicate display edges,
347    /// display edges with coincident endpoints, and display edges outside the
348    /// vertex array.
349    pub fn with_display_edges(
350        vertices: Vec<Vec3>,
351        triangle_indices: Vec<u32>,
352        display_edges: Vec<MeshEdge3d>,
353    ) -> Result<Self, Mesh3dError> {
354        Self::with_attributes(
355            vertices,
356            triangle_indices,
357            display_edges,
358            Mesh3dAttributes::new(),
359        )
360    }
361
362    /// Builds surfaces with one validated texture coordinate per model vertex.
363    ///
364    /// Duplicate model positions with different UVs are valid for atlas seams.
365    /// Winding and explicit display edges keep the untextured mesh contract.
366    /// A texture/material is attached only when uploading or binding to a
367    /// renderer; constructing this data requires no GPU dependencies.
368    pub fn textured(
369        vertices: Vec<Vec3>,
370        texture_coordinates: Vec<TextureCoordinate2d>,
371        triangle_indices: Vec<u32>,
372        display_edges: Vec<MeshEdge3d>,
373    ) -> Result<Self, Mesh3dError> {
374        if texture_coordinates.len() != vertices.len() {
375            return Err(Mesh3dError::TextureCoordinateCountMismatch {
376                vertex_count: vertices.len(),
377                coordinate_count: texture_coordinates.len(),
378            });
379        }
380        Self::with_attributes(
381            vertices,
382            triangle_indices,
383            display_edges,
384            Mesh3dAttributes::new().with_texture_coordinates(texture_coordinates),
385        )
386    }
387
388    /// Builds topology with optional UVs and normalized straight-linear colors.
389    /// Supplied attributes must match every vertex, including unused vertices.
390    /// Missing colors multiply by white. Opaque ignores alpha; Mask and Blend
391    /// use combined vertex/material/texture alpha. All buffers are moved into immutable shared storage without copies.
392    pub fn with_attributes(
393        vertices: Vec<Vec3>,
394        triangle_indices: Vec<u32>,
395        display_edges: Vec<MeshEdge3d>,
396        attributes: Mesh3dAttributes,
397    ) -> Result<Self, Mesh3dError> {
398        if let Some(coordinates) = &attributes.texture_coordinates
399            && coordinates.len() != vertices.len()
400        {
401            return Err(Mesh3dError::TextureCoordinateCountMismatch {
402                vertex_count: vertices.len(),
403                coordinate_count: coordinates.len(),
404            });
405        }
406        if let Some(colors) = &attributes.vertex_colors
407            && colors.len() != vertices.len()
408        {
409            return Err(Mesh3dError::VertexColorCountMismatch {
410                vertex_count: vertices.len(),
411                color_count: colors.len(),
412            });
413        }
414        if let Some(normals) = &attributes.normals
415            && normals.len() != vertices.len()
416        {
417            return Err(Mesh3dError::NormalCountMismatch {
418                vertex_count: vertices.len(),
419                normal_count: normals.len(),
420            });
421        }
422        if vertices.is_empty() {
423            return Err(Mesh3dError::EmptyVertices);
424        }
425        if triangle_indices.is_empty() && display_edges.is_empty() {
426            return Err(Mesh3dError::EmptyGeometry);
427        }
428        if !triangle_indices.len().is_multiple_of(3) {
429            return Err(Mesh3dError::InvalidTriangleIndexCount {
430                index_count: triangle_indices.len(),
431            });
432        }
433
434        for (triangle, indices) in triangle_indices.chunks_exact(3).enumerate() {
435            let [first, second, third] = [indices[0], indices[1], indices[2]];
436            validate_index(first, vertices.len())?;
437            validate_index(second, vertices.len())?;
438            validate_index(third, vertices.len())?;
439            if first == second
440                || second == third
441                || first == third
442                || triangle_is_degenerate(
443                    vertices[first as usize],
444                    vertices[second as usize],
445                    vertices[third as usize],
446                )
447            {
448                return Err(Mesh3dError::DegenerateTriangle { triangle });
449            }
450        }
451
452        for edge in &display_edges {
453            validate_index(edge.start, vertices.len())?;
454            validate_index(edge.end, vertices.len())?;
455            if vertices[edge.start as usize] == vertices[edge.end as usize] {
456                return Err(Mesh3dError::DegenerateDisplayEdge {
457                    start: edge.start,
458                    end: edge.end,
459                });
460            }
461        }
462
463        let canonical_bytes = display_edges
464            .len()
465            .checked_mul(std::mem::size_of::<((u32, u32), usize)>())
466            .ok_or(Mesh3dError::AllocationFailed {
467                requested_bytes: usize::MAX,
468            })?;
469        let mut canonical_edges = Vec::new();
470        canonical_edges
471            .try_reserve_exact(display_edges.len())
472            .map_err(|_| Mesh3dError::AllocationFailed {
473                requested_bytes: canonical_bytes,
474            })?;
475        for (index, edge) in display_edges.iter().enumerate() {
476            canonical_edges.push((edge.canonical(), index));
477        }
478        canonical_edges.sort_unstable_by_key(|entry| entry.0);
479        if let Some(pair) = canonical_edges
480            .windows(2)
481            .find(|pair| pair[0].0 == pair[1].0)
482        {
483            let duplicate = display_edges[pair[0].1.max(pair[1].1)];
484            return Err(Mesh3dError::DuplicateDisplayEdge {
485                start: duplicate.start,
486                end: duplicate.end,
487            });
488        }
489
490        let (bounds_min, bounds_max) = mesh_bounds(&vertices);
491        Ok(Self {
492            // One fixed-size Arc control block makes Mesh3d cloning O(1)
493            // without copying any caller-scale topology buffers.
494            storage: Arc::new(Mesh3dStorage {
495                vertices,
496                triangle_indices,
497                display_edges,
498                texture_coordinates: attributes.texture_coordinates.unwrap_or_default(),
499                vertex_colors: attributes.vertex_colors.unwrap_or_default(),
500                normals: attributes.normals.unwrap_or_default(),
501            }),
502            bounds_min,
503            bounds_max,
504        })
505    }
506
507    /// Returns immutable model-space vertices.
508    pub fn vertices(&self) -> &[Vec3] {
509        &self.storage.vertices
510    }
511
512    /// Returns the flat host-wound triangle index list.
513    pub fn triangle_indices(&self) -> &[u32] {
514        &self.storage.triangle_indices
515    }
516
517    /// Returns explicit mathematical edges, excluding triangulation diagonals.
518    pub fn display_edges(&self) -> &[MeshEdge3d] {
519        &self.storage.display_edges
520    }
521
522    /// Returns per-vertex normalized UVs, or an empty slice for untextured data.
523    pub fn texture_coordinates(&self) -> &[TextureCoordinate2d] {
524        &self.storage.texture_coordinates
525    }
526
527    /// Returns normalized straight-linear vertex RGBA, or empty for white.
528    /// The opaque surface pass ignores alpha; mathematical edges are unaffected.
529    pub fn vertex_colors(&self) -> &[Color] {
530        &self.storage.vertex_colors
531    }
532
533    /// Returns normalized application-supplied model normals, or an empty slice.
534    /// Lambert surfaces require normals; Unlit surfaces never evaluate them.
535    pub fn normals(&self) -> &[Vec3] {
536        &self.storage.normals
537    }
538
539    /// Returns the number of retained triangles.
540    pub fn triangle_count(&self) -> usize {
541        self.storage.triangle_indices.len() / 3
542    }
543
544    /// Returns the inclusive model-space lower bound.
545    pub const fn bounds_min(&self) -> Vec3 {
546        self.bounds_min
547    }
548
549    /// Returns the inclusive model-space upper bound.
550    pub const fn bounds_max(&self) -> Vec3 {
551        self.bounds_max
552    }
553
554    /// Returns retained CPU capacity bytes for topology and optional attributes.
555    pub fn recovery_memory_bytes(&self) -> usize {
556        self.storage
557            .vertices
558            .capacity()
559            .saturating_mul(std::mem::size_of::<Vec3>())
560            .saturating_add(
561                self.storage
562                    .triangle_indices
563                    .capacity()
564                    .saturating_mul(std::mem::size_of::<u32>()),
565            )
566            .saturating_add(
567                self.storage
568                    .display_edges
569                    .capacity()
570                    .saturating_mul(std::mem::size_of::<MeshEdge3d>()),
571            )
572            .saturating_add(
573                self.storage
574                    .texture_coordinates
575                    .capacity()
576                    .saturating_mul(std::mem::size_of::<TextureCoordinate2d>()),
577            )
578            .saturating_add(
579                self.storage
580                    .vertex_colors
581                    .capacity()
582                    .saturating_mul(std::mem::size_of::<Color>()),
583            )
584            .saturating_add(
585                self.storage
586                    .normals
587                    .capacity()
588                    .saturating_mul(std::mem::size_of::<Vec3>()),
589            )
590    }
591}
592
593/// Rejection reason for retained 3D topology.
594#[derive(Debug, Clone, Copy, PartialEq, Eq)]
595pub enum Mesh3dError {
596    /// A supplied normal is zero or cannot be normalized to a finite direction.
597    InvalidVertexNormal {
598        /// Source attribute index, including unused vertices.
599        vertex_index: usize,
600    },
601    /// Explicit normals must match every model vertex, including unused ones.
602    NormalCountMismatch {
603        /// Number of model vertices.
604        vertex_count: usize,
605        /// Number of supplied normals.
606        normal_count: usize,
607    },
608    /// A vertex color contains a non-finite or non-normalized channel.
609    InvalidVertexColor {
610        /// Zero-based source vertex/attribute index, including unused vertices.
611        vertex_index: usize,
612    },
613    /// An explicitly supplied color array must cover every model vertex.
614    VertexColorCountMismatch {
615        /// Number of model vertices.
616        vertex_count: usize,
617        /// Number of supplied straight-linear RGBA values.
618        color_count: usize,
619    },
620    /// A U/V component was non-finite or outside normalized `0..=1` bounds.
621    InvalidTextureCoordinate,
622    /// Textured topology must supply exactly one UV for each model vertex.
623    TextureCoordinateCountMismatch {
624        /// Number of model-space vertices.
625        vertex_count: usize,
626        /// Number of normalized texture coordinates provided.
627        coordinate_count: usize,
628    },
629    /// A retained mesh requires at least one model-space vertex.
630    EmptyVertices,
631    /// A retained mesh requires at least one triangle or display edge.
632    EmptyGeometry,
633    /// The triangle index list was not divisible by three.
634    InvalidTriangleIndexCount {
635        /// Rejected number of indices.
636        index_count: usize,
637    },
638    /// A triangle or display edge referenced a missing vertex.
639    IndexOutOfBounds {
640        /// Rejected vertex index.
641        index: u32,
642        /// Number of vertices available in the mesh.
643        vertex_count: usize,
644    },
645    /// A triangle repeated a vertex or had zero model-space area.
646    DegenerateTriangle {
647        /// Zero-based triangle number in the index list.
648        triangle: usize,
649    },
650    /// A display edge used one index twice or referenced coincident vertices.
651    DegenerateDisplayEdge {
652        /// First endpoint in the rejected declaration.
653        start: u32,
654        /// Second endpoint in the rejected declaration.
655        end: u32,
656    },
657    /// The same undirected display edge appeared more than once.
658    DuplicateDisplayEdge {
659        /// First endpoint in the rejected declaration.
660        start: u32,
661        /// Second endpoint in the rejected declaration.
662        end: u32,
663    },
664    /// Temporary validation storage could not be reserved.
665    AllocationFailed {
666        /// Bytes requested for duplicate-edge validation.
667        requested_bytes: usize,
668    },
669}
670
671impl fmt::Display for Mesh3dError {
672    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
673        match self {
674            Self::InvalidVertexNormal { vertex_index } => write!(
675                formatter,
676                "3D vertex {vertex_index} normal must be a nonzero finite direction"
677            ),
678            Self::NormalCountMismatch {
679                vertex_count,
680                normal_count,
681            } => write!(
682                formatter,
683                "{vertex_count} mesh vertices require matching normals, got {normal_count}"
684            ),
685            Self::InvalidVertexColor { vertex_index } => write!(
686                formatter,
687                "3D vertex {vertex_index} color must be finite straight-linear RGBA in 0..=1"
688            ),
689            Self::VertexColorCountMismatch {
690                vertex_count,
691                color_count,
692            } => write!(
693                formatter,
694                "{vertex_count} mesh vertices require matching colors, got {color_count}"
695            ),
696            Self::InvalidTextureCoordinate => {
697                write!(formatter, "texture coordinates must be finite in 0..=1")
698            }
699            Self::TextureCoordinateCountMismatch {
700                vertex_count,
701                coordinate_count,
702            } => write!(
703                formatter,
704                "{vertex_count} mesh vertices require matching UVs, got {coordinate_count}"
705            ),
706            Self::EmptyVertices => write!(formatter, "3D mesh requires at least one vertex"),
707            Self::EmptyGeometry => {
708                write!(formatter, "3D mesh requires triangles or display edges")
709            }
710            Self::InvalidTriangleIndexCount { index_count } => write!(
711                formatter,
712                "3D mesh triangle index count, when present, must be divisible by three, got {index_count}"
713            ),
714            Self::IndexOutOfBounds {
715                index,
716                vertex_count,
717            } => write!(
718                formatter,
719                "3D mesh index {index} is outside {vertex_count} vertices"
720            ),
721            Self::DegenerateTriangle { triangle } => {
722                write!(formatter, "3D mesh triangle {triangle} has zero area")
723            }
724            Self::DegenerateDisplayEdge { start, end } => {
725                write!(formatter, "3D display edge {start}-{end} has zero length")
726            }
727            Self::DuplicateDisplayEdge { start, end } => {
728                write!(formatter, "3D display edge {start}-{end} is duplicated")
729            }
730            Self::AllocationFailed { requested_bytes } => write!(
731                formatter,
732                "could not reserve {requested_bytes} bytes for 3D mesh validation"
733            ),
734        }
735    }
736}
737
738impl Error for Mesh3dError {}
739
740fn validate_index(index: u32, vertex_count: usize) -> Result<(), Mesh3dError> {
741    ((index as u64) < vertex_count as u64)
742        .then_some(())
743        .ok_or(Mesh3dError::IndexOutOfBounds {
744            index,
745            vertex_count,
746        })
747}
748
749fn triangle_is_degenerate(first: Vec3, second: Vec3, third: Vec3) -> bool {
750    let ab = (
751        second.x() as f64 - first.x() as f64,
752        second.y() as f64 - first.y() as f64,
753        second.z() as f64 - first.z() as f64,
754    );
755    let ac = (
756        third.x() as f64 - first.x() as f64,
757        third.y() as f64 - first.y() as f64,
758        third.z() as f64 - first.z() as f64,
759    );
760    let cross = (
761        ab.1 * ac.2 - ab.2 * ac.1,
762        ab.2 * ac.0 - ab.0 * ac.2,
763        ab.0 * ac.1 - ab.1 * ac.0,
764    );
765    cross.0 == 0.0 && cross.1 == 0.0 && cross.2 == 0.0
766}
767
768fn mesh_bounds(vertices: &[Vec3]) -> (Vec3, Vec3) {
769    let first = vertices[0];
770    let mut minimum = [first.x(), first.y(), first.z()];
771    let mut maximum = minimum;
772    for vertex in &vertices[1..] {
773        let components = [vertex.x(), vertex.y(), vertex.z()];
774        for axis in 0..3 {
775            minimum[axis] = minimum[axis].min(components[axis]);
776            maximum[axis] = maximum[axis].max(components[axis]);
777        }
778    }
779    (
780        Vec3::new_unchecked(minimum[0], minimum[1], minimum[2]),
781        Vec3::new_unchecked(maximum[0], maximum[1], maximum[2]),
782    )
783}
784
785#[cfg(test)]
786mod tests {
787    use super::{
788        Mesh3d, Mesh3dError, Mesh3dStyleError, MeshEdge3d, MeshStyle3d, SurfaceStyle3d,
789        WireframeStyle3d,
790    };
791    use crate::{Color, LogicalPixels, UnitError, Vec3};
792
793    fn vector(x: f32, y: f32, z: f32) -> Vec3 {
794        Vec3::new(x, y, z).unwrap()
795    }
796
797    fn logical(value: f32) -> LogicalPixels {
798        LogicalPixels::new(value).unwrap()
799    }
800
801    #[test]
802    fn texture_coordinates_are_finite_normalized_and_match_vertices() {
803        use super::TextureCoordinate2d;
804        for value in [f32::NAN, f32::INFINITY, -f32::INFINITY, -0.01, 1.01] {
805            assert_eq!(
806                TextureCoordinate2d::new(value, 0.0),
807                Err(Mesh3dError::InvalidTextureCoordinate)
808            );
809            assert_eq!(
810                TextureCoordinate2d::new(0.0, value),
811                Err(Mesh3dError::InvalidTextureCoordinate)
812            );
813        }
814        let uv = TextureCoordinate2d::new(0.0, 1.0).unwrap();
815        assert_eq!((uv.u(), uv.v()), (0.0, 1.0));
816        let vertices = vec![Vec3::ZERO, Vec3::X, Vec3::Y];
817        for count in [0, 2, 4] {
818            assert_eq!(
819                Mesh3d::textured(vertices.clone(), vec![uv; count], vec![0, 1, 2], Vec::new()),
820                Err(Mesh3dError::TextureCoordinateCountMismatch {
821                    vertex_count: 3,
822                    coordinate_count: count
823                })
824            );
825        }
826        let bare = Mesh3d::new(vertices.clone(), vec![0, 1, 2]).unwrap();
827        let mesh = Mesh3d::textured(vertices, vec![uv; 3], vec![0, 1, 2], Vec::new()).unwrap();
828        assert_eq!(mesh.texture_coordinates(), &[uv; 3]);
829        assert_eq!(
830            mesh.recovery_memory_bytes(),
831            bare.recovery_memory_bytes() + 3 * std::mem::size_of::<TextureCoordinate2d>()
832        );
833        assert_eq!(
834            mesh.clone().texture_coordinates().as_ptr(),
835            mesh.texture_coordinates().as_ptr()
836        );
837    }
838
839    #[test]
840    fn mesh_validates_topology_and_preserves_explicit_edges() {
841        let mesh = Mesh3d::with_display_edges(
842            vec![
843                vector(-1.0, -1.0, 0.0),
844                vector(1.0, -1.0, 0.0),
845                vector(0.0, 1.0, 0.0),
846            ],
847            vec![0, 1, 2],
848            vec![
849                MeshEdge3d::new(0, 1).unwrap(),
850                MeshEdge3d::new(1, 2).unwrap(),
851            ],
852        )
853        .unwrap();
854        assert_eq!(mesh.triangle_count(), 1);
855        assert_eq!(mesh.display_edges().len(), 2);
856        assert_eq!(mesh.bounds_min(), vector(-1.0, -1.0, 0.0));
857        assert_eq!(mesh.bounds_max(), vector(1.0, 1.0, 0.0));
858    }
859
860    #[test]
861    fn mesh_rejects_invalid_and_degenerate_topology() {
862        assert_eq!(
863            Mesh3d::new(Vec::new(), vec![0, 1, 2]),
864            Err(Mesh3dError::EmptyVertices)
865        );
866        let vertices = vec![
867            vector(0.0, 0.0, 0.0),
868            vector(1.0, 0.0, 0.0),
869            vector(2.0, 0.0, 0.0),
870        ];
871        assert_eq!(
872            Mesh3d::new(vertices.clone(), vec![0, 1]),
873            Err(Mesh3dError::InvalidTriangleIndexCount { index_count: 2 })
874        );
875        assert_eq!(
876            Mesh3d::new(vertices.clone(), vec![0, 1, 3]),
877            Err(Mesh3dError::IndexOutOfBounds {
878                index: 3,
879                vertex_count: 3,
880            })
881        );
882        assert_eq!(
883            Mesh3d::new(vertices, vec![0, 1, 2]),
884            Err(Mesh3dError::DegenerateTriangle { triangle: 0 })
885        );
886    }
887
888    #[test]
889    fn mesh_rejects_duplicate_undirected_display_edges() {
890        let vertices = vec![
891            vector(0.0, 0.0, 0.0),
892            vector(1.0, 0.0, 0.0),
893            vector(0.0, 1.0, 0.0),
894        ];
895        assert_eq!(
896            Mesh3d::with_display_edges(
897                vertices,
898                vec![0, 1, 2],
899                vec![
900                    MeshEdge3d::new(0, 1).unwrap(),
901                    MeshEdge3d::new(1, 0).unwrap(),
902                ],
903            ),
904            Err(Mesh3dError::DuplicateDisplayEdge { start: 1, end: 0 })
905        );
906        assert_eq!(
907            MeshEdge3d::new(2, 2),
908            Err(Mesh3dError::DegenerateDisplayEdge { start: 2, end: 2 })
909        );
910    }
911
912    #[test]
913    fn mesh_rejects_geometrically_zero_length_display_edges() {
914        assert_eq!(
915            Mesh3d::with_display_edges(
916                vec![vector(1.0, 2.0, 3.0), vector(1.0, 2.0, 3.0)],
917                Vec::new(),
918                vec![MeshEdge3d::new(0, 1).unwrap()],
919            ),
920            Err(Mesh3dError::DegenerateDisplayEdge { start: 0, end: 1 })
921        );
922    }
923
924    #[test]
925    fn mesh_accepts_edge_only_construction_geometry() {
926        let mesh = Mesh3d::with_display_edges(
927            vec![vector(0.0, 0.0, 0.0), vector(1.0, 0.0, 0.0)],
928            Vec::new(),
929            vec![MeshEdge3d::new(0, 1).unwrap()],
930        )
931        .unwrap();
932        assert_eq!(mesh.triangle_count(), 0);
933        assert_eq!(mesh.display_edges().len(), 1);
934        assert_eq!(
935            Mesh3d::new(vec![vector(0.0, 0.0, 0.0)], Vec::new()),
936            Err(Mesh3dError::EmptyGeometry)
937        );
938    }
939
940    #[test]
941    fn wireframe_style_validates_logical_pixel_contract() {
942        let style = WireframeStyle3d::visible(Color::WHITE, logical(2.0))
943            .unwrap()
944            .with_hidden(
945                Color::rgba(0.5, 0.5, 0.5, 1.0),
946                logical(1.5),
947                logical(6.0),
948                logical(4.0),
949            )
950            .unwrap();
951        assert_eq!(style.visible_width(), logical(2.0));
952        assert_eq!(style.hidden_pattern(), Some((logical(6.0), logical(4.0))));
953        assert_eq!(
954            LogicalPixels::new(0.0),
955            Err(UnitError::InvalidLogicalPixels { value: 0.0 })
956        );
957        assert_eq!(
958            WireframeStyle3d::visible(Color::WHITE, logical(f32::MAX)),
959            Err(Mesh3dStyleError::InvalidColorOrWidth)
960        );
961        assert_eq!(
962            WireframeStyle3d::visible(Color::WHITE, logical(f32::MIN_POSITIVE / 2.0)),
963            Err(Mesh3dStyleError::InvalidColorOrWidth)
964        );
965        assert_eq!(
966            WireframeStyle3d::visible(Color::rgb(-0.01, 0.0, 0.0), logical(1.0)),
967            Err(Mesh3dStyleError::InvalidColorOrWidth)
968        );
969        assert_eq!(
970            WireframeStyle3d::visible(Color::WHITE, logical(1.0))
971                .unwrap()
972                .with_hidden(Color::WHITE, logical(1.0), logical(f32::MAX), logical(2.0),),
973            Err(Mesh3dStyleError::InvalidDashPattern)
974        );
975        assert_eq!(
976            WireframeStyle3d::visible(Color::WHITE, logical(1.0))
977                .unwrap()
978                .with_hidden(
979                    Color::WHITE,
980                    logical(1.0),
981                    logical(f32::MIN_POSITIVE / 2.0),
982                    logical(2.0),
983                ),
984            Err(Mesh3dStyleError::InvalidDashPattern)
985        );
986        assert_eq!(
987            WireframeStyle3d::visible(Color::WHITE, logical(1.0))
988                .unwrap()
989                .with_hidden(
990                    Color::WHITE,
991                    logical(1.0),
992                    logical(f32::MAX),
993                    logical(f32::MAX),
994                ),
995            Err(Mesh3dStyleError::InvalidDashPattern)
996        );
997    }
998
999    #[test]
1000    fn mesh_style_keeps_surface_and_wireframe_extensible() {
1001        let surface = SurfaceStyle3d::opaque(Color::rgb(0.2, 0.3, 0.4)).unwrap();
1002        let wireframe = WireframeStyle3d::visible(Color::WHITE, logical(2.0)).unwrap();
1003        let style = MeshStyle3d::surface(surface).with_wireframe(wireframe);
1004        assert_eq!(style.surface_style(), Some(surface));
1005        assert_eq!(style.wireframe_style(), Some(wireframe));
1006        assert_eq!(
1007            SurfaceStyle3d::opaque(Color::rgba(1.0, 1.0, 1.0, 0.5)),
1008            Err(Mesh3dStyleError::InvalidSurfaceColor)
1009        );
1010        assert_eq!(
1011            SurfaceStyle3d::opaque(Color::rgb(1.01, 0.0, 0.0)),
1012            Err(Mesh3dStyleError::InvalidSurfaceColor)
1013        );
1014        assert_eq!(MeshStyle3d::wireframe(wireframe).surface_style(), None);
1015    }
1016}