ifc_lite_geometry/mesh_check/
shape.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//! Triangle shape as the mesh census reads it.
6//!
7//! One measure for the repo: a triangle's longest edge over its altitude onto
8//! that edge. It is what `mesh_census` reports and what
9//! `scripts/mesh-census-compare.mjs` judges a geometry change by, so code that
10//! decides between two triangulations asks the same question here.
11
12use crate::mesh::Mesh;
13
14/// Longest edge over altitude above which a triangle is a sliver: the bar of
15/// `mesh_census`.
16const SLIVER_ASPECT: f64 = 50.0;
17
18/// The census's shape reading of a mesh.
19#[derive(Debug, Clone, Copy, PartialEq)]
20pub struct TriangleShape {
21    /// Triangles past [`SLIVER_ASPECT`].
22    pub slivers: usize,
23    /// The worst aspect of any triangle with area; 0 for a mesh without one.
24    pub max_aspect: f64,
25}
26
27/// Read `mesh` as the census does. Triangles without area and triangles naming
28/// a vertex the mesh does not have are left out, as there.
29pub fn triangle_shape(mesh: &Mesh) -> TriangleShape {
30    let point = |i: u32| -> Option<[f64; 3]> {
31        let start = (i as usize).checked_mul(3)?;
32        let p = mesh.positions.get(start..start.checked_add(3)?)?;
33        Some([f64::from(p[0]), f64::from(p[1]), f64::from(p[2])])
34    };
35    let mut shape = TriangleShape { slivers: 0, max_aspect: 0.0 };
36    for t in mesh.indices.chunks_exact(3) {
37        let (Some(a), Some(b), Some(c)) = (point(t[0]), point(t[1]), point(t[2])) else {
38            continue;
39        };
40        let sub = |p: [f64; 3], q: [f64; 3]| [p[0] - q[0], p[1] - q[1], p[2] - q[2]];
41        let dot = |p: [f64; 3], q: [f64; 3]| p[0] * q[0] + p[1] * q[1] + p[2] * q[2];
42        let (u, v, w) = (sub(b, a), sub(c, a), sub(c, b));
43        let n = [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]];
44        let twice_area = dot(n, n).sqrt();
45        if twice_area <= 0.0 {
46            continue;
47        }
48        // Longest edge squared over twice the area: the edge over its altitude.
49        let aspect = dot(u, u).max(dot(v, v)).max(dot(w, w)) / twice_area;
50        shape.max_aspect = shape.max_aspect.max(aspect);
51        shape.slivers += usize::from(aspect > SLIVER_ASPECT);
52    }
53    shape
54}