ifc_lite_testkit/
mesh.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! Mesh oracles over raw `positions` (xyz triples) / `indices` slices.
6//!
7//! Test code used to re-derive these per file with different vertex keying
8//! and tolerances, so the same regression could pass one test and fail
9//! another purely because of the oracle. The keying is now an explicit
10//! argument ([`Key`]).
11
12use ifc_lite_geometry::mesh::Mesh;
13pub use ifc_lite_geometry::mesh_check::TriangleShape;
14use ifc_lite_geometry::mesh_check::{self, Degenerate, EdgeLedger, VertexKey};
15
16/// How vertices are identified when counting shared edges.
17#[derive(Clone, Copy, Debug)]
18pub enum Key {
19    /// Exact `f32` values, no tolerance. `-0.0` and `+0.0` are the SAME
20    /// vertex (they compare equal as floats; keying on raw bits would split a
21    /// shared corner and report phantom open edges). NaN positions with equal
22    /// bits are equal to each other; callers wanting NaN rejected should
23    /// check for it first.
24    Bits,
25    /// Snap to a grid of the given pitch (world units).
26    Grid(f64),
27}
28
29impl Key {
30    fn vertex_key(self) -> VertexKey {
31        match self {
32            Key::Bits => VertexKey::BitsZeroFolded,
33            Key::Grid(pitch) => VertexKey::GridDiv(pitch),
34        }
35    }
36}
37
38/// Axis-aligned bounds `(min, max)`; `([inf;3], [-inf;3])` when empty.
39///
40/// NaN is explicit, never silently skipped (`f32::min` would drop it and hide
41/// a corrupt mesh from the oracle): an axis holding any NaN coordinate reports
42/// `NaN` for both its min and max, so a following comparison fails loudly.
43pub fn bbox(positions: &[f32]) -> ([f32; 3], [f32; 3]) {
44    let mut min = [f32::INFINITY; 3];
45    let mut max = [f32::NEG_INFINITY; 3];
46    let mut nan = [false; 3];
47    for p in positions.chunks_exact(3) {
48        for a in 0..3 {
49            if p[a].is_nan() {
50                nan[a] = true;
51            }
52            min[a] = min[a].min(p[a]);
53            max[a] = max[a].max(p[a]);
54        }
55    }
56    for a in 0..3 {
57        if nan[a] {
58            min[a] = f32::NAN;
59            max[a] = f32::NAN;
60        }
61    }
62    (min, max)
63}
64
65/// Signed volume by the divergence theorem, accumulated in `f64` about the
66/// bounding-box centre ([`mesh_check::signed_volume`]). Referencing the centre
67/// (not the world origin) keeps the result translation-stable for open meshes
68/// and far-from-origin operands. Positive for outward (CCW) winding.
69pub fn signed_volume(positions: &[f32], indices: &[u32]) -> f64 {
70    let mut mesh = Mesh::new();
71    mesh.positions = positions.to_vec();
72    mesh.indices = indices.to_vec();
73    mesh_check::signed_volume(&mesh)
74}
75
76/// Triangle shape as the mesh census reads it
77/// ([`mesh_check::triangle_shape`]): the triangles past 50:1 by longest edge
78/// over altitude, and the worst such aspect.
79pub fn triangle_shape(positions: &[f32], indices: &[u32]) -> TriangleShape {
80    let mut mesh = Mesh::new();
81    mesh.positions = positions.to_vec();
82    mesh.indices = indices.to_vec();
83    mesh_check::triangle_shape(&mesh)
84}
85
86/// Number of undirected edges whose incidence count is not exactly 2
87/// (boundary edges plus non-manifold edges). Zero for a closed 2-manifold.
88/// Zero-length edges (both ends on one key) are ignored.
89pub fn open_edges(positions: &[f32], indices: &[u32], key: Key) -> usize {
90    EdgeLedger::build_raw(positions, indices, key.vertex_key(), Degenerate::SkipEdge).undirected_defects()
91}
92
93#[cfg(test)]
94mod tests {
95    use super::*;
96
97    /// Outward-wound axis-aligned box at `lo` with edge lengths `s`.
98    fn cube(lo: [f32; 3], s: f32) -> (Vec<f32>, Vec<u32>) {
99        let mut p = Vec::new();
100        for i in 0..8u32 {
101            p.extend([lo[0] + s * (i & 1) as f32, lo[1] + s * ((i >> 1) & 1) as f32, lo[2] + s * ((i >> 2) & 1) as f32]);
102        }
103        let quads: [[u32; 4]; 6] = [[0, 2, 3, 1], [4, 5, 7, 6], [0, 1, 5, 4], [2, 6, 7, 3], [0, 4, 6, 2], [1, 3, 7, 5]];
104        let idx = quads.iter().flat_map(|q| [q[0], q[1], q[2], q[0], q[2], q[3]]).collect();
105        (p, idx)
106    }
107
108    #[test]
109    fn unit_cube_is_closed_with_unit_volume() {
110        let (p, i) = cube([0.0; 3], 1.0);
111        assert!((signed_volume(&p, &i) - 1.0).abs() < 1e-12);
112        assert_eq!(open_edges(&p, &i, Key::Bits), 0);
113        assert_eq!(open_edges(&p, &i, Key::Grid(1e-4)), 0);
114    }
115
116    #[test]
117    fn volume_is_translation_stable_far_from_the_origin() {
118        let (p, i) = cube([10_000.0, -10_000.0, 5_000.0], 2.0);
119        assert!((signed_volume(&p, &i) - 8.0).abs() < 1e-9);
120    }
121
122    #[test]
123    fn dropping_a_triangle_opens_edges_and_flipping_negates_volume() {
124        let (p, i) = cube([0.0; 3], 1.0);
125        assert_eq!(open_edges(&p, &i[3..], Key::Bits), 3);
126        let flipped: Vec<u32> = i.chunks_exact(3).flat_map(|t| [t[0], t[2], t[1]]).collect();
127        assert!((signed_volume(&p, &flipped) + 1.0).abs() < 1e-12);
128    }
129
130    #[test]
131    fn grid_key_welds_vertices_that_exact_bits_keep_apart() {
132        let (mut p, i) = cube([0.0; 3], 1.0);
133        // Duplicate vertex 0 as a hair-offset twin used by the first triangle only.
134        p.extend([1e-7, 0.0, 0.0]);
135        let mut split = i.clone();
136        split[0] = 8;
137        assert!(open_edges(&p, &split, Key::Bits) > 0);
138        assert_eq!(open_edges(&p, &split, Key::Grid(1e-4)), 0);
139    }
140
141    #[test]
142    fn negative_zero_is_the_same_vertex_as_positive_zero_under_bits() {
143        // A triangle fan whose shared corner is written +0.0 in one triangle and
144        // -0.0 in the other: closed as floats, "open" if keyed on raw bits.
145        let p = [0.0f32, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, -0.0, -0.0, -0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0];
146        // Two coincident triangles with opposite winding bound a closed sheet.
147        let i = [0u32, 1, 2, 3, 5, 4];
148        assert_eq!(open_edges(&p, &i, Key::Bits), 0);
149        assert_eq!(open_edges(&p, &i, Key::Grid(1e-4)), 0);
150    }
151
152    #[test]
153    fn bbox_reports_nan_instead_of_skipping_it() {
154        let (min, max) = bbox(&[0.0, 1.0, 2.0, f32::NAN, 3.0, 4.0]);
155        assert!(min[0].is_nan() && max[0].is_nan(), "NaN axis is NaN, not 0.0");
156        assert_eq!((min[1], max[1]), (1.0, 3.0));
157        assert_eq!((min[2], max[2]), (2.0, 4.0));
158    }
159
160    #[test]
161    fn bbox_of_empty_is_inverted() {
162        let (min, max) = bbox(&[]);
163        assert!(min[0] > max[0]);
164    }
165}