ifc_lite_geometry/mesh_check/
volume.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//! Signed volume of a triangle mesh by the divergence theorem.
6
7use crate::kernel::signed_volume::tetra_volume6;
8use crate::mesh::Mesh;
9
10/// Signed volume of a (closed) triangle mesh via the divergence theorem, about
11/// [`volume_reference`] of the same mesh. Reads the f32 positions unsnapped; an
12/// out-of-range index panics. Positive for outward (CCW) winding.
13pub fn signed_volume(mesh: &Mesh) -> f64 {
14    signed_volume_about(mesh, &volume_reference(mesh))
15}
16
17/// The point [`signed_volume`] sums `mesh` about: the centre of its position
18/// bounds (the origin for an empty mesh). `kernel::signed_volume` uses the same
19/// rule over the vertices its triangles reference, so the two agree unless the
20/// buffer holds unreferenced positions. On native, positions are absolute, and
21/// an open surface's divergence sum grows with the distance to the reference
22/// point, so the point must lie within the operand's extent, not at the world
23/// origin. Read off `Mesh::bounds`, a linear scan of the position buffer, so
24/// the sum itself is the only index walk.
25pub fn volume_reference(mesh: &Mesh) -> [f64; 3] {
26    if mesh.is_empty() {
27        return [0.0; 3];
28    }
29    let (lo, hi) = mesh.bounds();
30    [
31        (f64::from(lo.x) + f64::from(hi.x)) * 0.5,
32        (f64::from(lo.y) + f64::from(hi.y)) * 0.5,
33        (f64::from(lo.z) + f64::from(hi.z)) * 0.5,
34    ]
35}
36
37/// [`signed_volume`] about a caller-chosen `o`, in one walk. A before/after
38/// difference over the same host must read both meshes about ONE point (the
39/// host's [`volume_reference`]): the flux of a crack the cut did not touch then
40/// cancels, where two per-mesh points would leave `(o_after - o_before)·N/6` of
41/// it in the removed volume (#4632).
42pub fn signed_volume_about(mesh: &Mesh, o: &[f64; 3]) -> f64 {
43    mesh.indices
44        .chunks_exact(3)
45        .map(|t| tetra_volume6(&vertex(mesh, t[0]), &vertex(mesh, t[1]), &vertex(mesh, t[2]), o))
46        .sum::<f64>()
47        / 6.0
48}
49
50#[inline]
51fn vertex(mesh: &Mesh, i: u32) -> [f64; 3] {
52    let b = i as usize * 3;
53    [mesh.positions[b] as f64, mesh.positions[b + 1] as f64, mesh.positions[b + 2] as f64]
54}