Measure: a body whose meshes leave a gap keeps its volume wherever it is (#2069)

* Measure: a body whose meshes leave a gap keeps its volume wherever it is

A part ring cut by solid.combine (two prisms through its ends, a notch
through its chamfer) measured 992.03 mm3 at the origin, 999.17 moved
100 mm and 1063.48 moved 1000 mm; it encloses 993.92. The reference
mesher leaves a crack where the notch meets the chamfer's cone: the
volume beside it is left out, and the divergence-theorem sums, taken
about the world origin, close the crack by a cone to the origin, so the
error grows with the body's distance from it.

A closed surface's area vectors sum to zero. When the picked meshes'
sum could move the volume by more than 1e-5 within the body's size, and
the display plan (which shares every edge's nodes between its faces) is
closed, the body is measured on the plan, about its box centre. Every
other body measures exactly as before.

Tests: the cut ring at the origin and moved by up to 10000 mm, against a
grid quadrature of the cut; a revolved ring of cones and cylinders moved
100/1000/10000 mm along each axis (1e-6); a cylinder and a frustum far
from the origin against hand values. Robustness seed 64 moves by 1.4e-6
and is recorded.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* Measure: a gap the display plan can't close is measured about the box's centre

When the meshes leave a gap and the display plan isn't closed either, the
sums used to fall back to the origin-based volume, which drifts with the
body's distance from the origin (7 % at 1000 mm for the part ring). The
per-face sums are now taken about the fine mesh's box centre, which closes
the gap by a cone to a point inside the body; over a closed mesh nothing
changes. The gap decision moves into gap_closed, and a unit test with a
cube left open by hand covers closed vs open meshes, the closed plan, and
the fallback with an open plan or none.

Seeds 14, 20, 40, 55 and 61 end with such a body and are recorded with
ROBUSTNESS_GOLDENS_BLESS (volumes move by -0.51 %, +0.16 %, +1.9e-4,
+9.0e-5 and -1.5e-5; steps, outcomes and counts unchanged).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* Record robustness seed 86 after measuring bodies whose meshes leave a gap

Seed 86 was added on main by #2387 after this branch's goldens were recorded. Its last
body leaves a gap in its meshes, so the measure change here moves its volume by -0.27 %
and its area by +0.13 %; steps, outcome and counts are unchanged. Seed 86 passes
unchanged on main 57d21013. Every other seed matches on the merged branch.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* measure: take the display plan only where it agrees with the sums to within what the gap could move

A closed display plan meshed less finely than the sums differs from them by its own chord error,
which can be larger than anything the gap explains: an imported part with small blends measured
0.03 % low on its plan. The plan is now taken only where the two differ by at most what the
gap's area could move the volume within the body's size; otherwise the sums about the box's
centre stand.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* measure: sum a mesh left open about its box's centre only, without the display plan

The closed display plan meshes some faces of an imported B-spline part
more coarsely than the sums do, so a body and its boolean pieces no
longer add up: clearance's union cross-check then refused a 17.3 mm3
overlap between two such parts (the pieces implied 20.5). Summing about
the box's centre alone keeps the gap closed by a cone to a point inside
the body and stays consistent with the pieces. Seeds 64 and 86 are
re-recorded with the reason.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* measure: placement tests in the area's test files

The ring and frustum tests join measure.rs's tests, and the cut ring
joins measure_centre_tests.rs (AGENTS.md: a regression test goes into
the existing test file for its area). The goldens note for seeds 14, 20,
40, 55 and 61 describes the centre-only sums.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* measure: keep the origin for a body left open on purpose

A surface, or a cup whose lid is still a separate sheet, has no volume of
its own. Measured about its box's centre, two such bodies stopped
comparing once the centre moved (a crowned lid rises), which broke the
patch crown test. Only a mesh with a small crack is measured about the
centre now.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Aac7mP9rthK3WsPpPRvCsF

* Robustness goldens: keep main's notes, one note for this change's seeds

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Aac7mP9rthK3WsPpPRvCsF

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
NOWN-DEV
2026-10-21 00:57:03 +00:00
committed by GitHub
parent 36c732ddb7
commit 63cb48a4ee
3 changed files with 199 additions and 12 deletions
+141 -5
View File
@@ -22,15 +22,21 @@ pub struct BodyMeasure {
pub merged: TopoCounts,
}
/// Per-face sums: area, 6 × signed volume and 24 × first moments (divergence theorem, origin 0).
fn face_sums(m: &Mesh, nf: usize) -> Vec<(f64, f64, Vec3)> {
let mut out = vec![(0.0, 0.0, Vec3::ZERO); nf];
/// Per-face sums: area, 6 × signed volume and 24 × first moments (divergence theorem), taken
/// about `o` (the moments relative to it), and the sum of the area vectors (zero over a closed
/// surface). Over a closed surface the volume does not depend on `o`; over one that leaves a
/// gap, the gap is closed by a cone to `o`, so `o` near the body keeps that cone small.
fn face_sums(m: &Mesh, nf: usize, o: Vec3) -> Vec<(f64, f64, Vec3, Vec3)> {
let mut out = vec![(0.0, 0.0, Vec3::ZERO, Vec3::ZERO); nf];
for (t, f) in m.triangles.iter().zip(&m.tri_face) {
let (Some([a, b, c]), Some(slot)) = (m.tri(t), out.get_mut(*f as usize)) else { continue };
let n = (b - a).cross(c - a) * 0.5;
let (a, b, c) = (a - o, b - o, c - o);
let d = a.dot(b.cross(c));
slot.0 += (b - a).cross(c - a).len() * 0.5;
slot.0 += n.len();
slot.1 += d;
slot.2 += (a + b + c) * d;
slot.3 += n;
}
out
}
@@ -152,7 +158,13 @@ fn mass(b: &Body, topology: bool) -> Result<(MassMeasure, Option<Mesh>)> {
None => None,
};
let nf = b.face_count();
let (sf, sm, sc) = (face_sums(&fine, nf), face_sums(&medium, nf), face_sums(&coarse, nf));
// About the box's centre when the meshes leave only a crack: see `face_sums`. A body that is
// open on purpose (a surface, or a cup whose lid is still a separate sheet) has no volume of
// its own; it keeps the origin, so such bodies still compare with each other when the centre
// of their boxes moves (a crowned lid rises, the open cup under it doesn't change).
let (surface, gap) = face_sums(&fine, nf, Vec3::ZERO).iter().fold((0.0, Vec3::ZERO), |s, f| (s.0 + f.0, s.1 + f.3));
let o = Some(fine.bounds().center()).filter(|c| c.is_finite() && gap.len() <= 0.01 * surface).unwrap_or(Vec3::ZERO);
let (sf, sm, sc) = (face_sums(&fine, nf, o), face_sums(&medium, nf, o), face_sums(&coarse, nf, o));
let close = |x: f64, y: f64| (x - y).abs() <= 0.01 * x.abs().max(y.abs()) + 1e-9;
let (mut area, mut v6, mut mom) = (0.0, 0.0, Vec3::ZERO);
for ((f, m), c) in sf.iter().zip(&sm).zip(&sc) {
@@ -168,6 +180,13 @@ fn mass(b: &Body, topology: bool) -> Result<(MassMeasure, Option<Mesh>)> {
v6 += pick.1;
mom += pick.2;
}
// The moments back about the origin. A gap the meshes leave (a crack where a trimmed face
// meets a hole cut into it) is closed by a cone to the box's centre, which keeps it small
// (a crack of 0.3 mm² moved a part ring's volume by 7 % about the origin 1000 mm away; about
// the centre, by 0.1 %). Every body is measured by the same meshes this way, so a body and the
// pieces a boolean cuts it into add up: a closed display plan measured instead would mesh
// some faces more coarsely than the sums do and break that.
let mom = o * (4.0 * v6) + mom;
let volume = v6 / 6.0;
let centroid = if v6.abs() > 1e-12 { mom / (4.0 * v6) } else { fine.bounds().center() };
Ok((MassMeasure { volume, area, centroid, bbox: coarse.bounds().union(&fine.bounds()) }, topo))
@@ -197,4 +216,121 @@ mod tests {
assert!((got - want).abs() < 1e-3 * want, "{got} against {want}");
assert!(measure(&ring).unwrap().merged.faces > 0);
}
/// A 10 mm cube at `at`, each side in n × n squares of two triangles, one face per side;
/// without its first `open` triangles.
fn cube(at: Vec3, n: usize, open: usize) -> Mesh {
let mut m = Mesh::default();
let s = 10.0;
for axis in 0..3 {
for side in [0.0, 1.0] {
for i in 0..n {
for j in 0..n {
let corner = |a: usize, b: usize| {
let mut c = [0.0; 3];
c[axis] = side * s;
c[(axis + 1) % 3] = a as f64 * s / n as f64;
c[(axis + 2) % 3] = b as f64 * s / n as f64;
at + Vec3::new(c[0], c[1], c[2])
};
let k = m.positions.len() as u32;
m.positions.extend([corner(i, j), corner(i + 1, j), corner(i + 1, j + 1), corner(i, j + 1)]);
m.triangles.extend(if side > 0.0 { [[k, k + 1, k + 2], [k, k + 2, k + 3]] } else { [[k, k + 2, k + 1], [k, k + 3, k + 2]] });
m.tri_face.extend([(2 * axis) as u32 + side as u32; 2]);
}
}
}
}
m.triangles.drain(..open);
m.tri_face.drain(..open);
m
}
/// The summed per-face sums of `m` about `o`, with the moments about the origin (as
/// `measure` passes them on).
fn sums(m: &Mesh, o: Vec3) -> (f64, f64, Vec3, Vec3) {
let (area, v6, mom, normal) =
face_sums(m, 6, o).iter().fold((0.0, 0.0, Vec3::ZERO, Vec3::ZERO), |s, f| (s.0 + f.0, s.1 + f.1, s.2 + f.2, s.3 + f.3));
(area, v6, o * (4.0 * v6) + mom, normal)
}
/// A cube 1000 mm from the origin with one 0.5 mm² facet left out: about the box's centre
/// the sums miss a cone of that facet to the centre (0.08 %), where about the origin they are
/// 17 % over. Closed, it measures the same about either.
#[test]
fn a_mesh_left_open_is_measured_about_its_centre() {
let at = Vec3::new(1000.0, 1000.0, 1000.0);
let (closed, open) = (cube(at, 10, 0), cube(at, 10, 1));
let centre = at + Vec3::new(5.0, 5.0, 5.0);
for o in [Vec3::ZERO, centre] {
let (area, v6, mom, normal) = sums(&closed, o);
assert!((area - 600.0).abs() < 1e-9 && (v6 / 6.0 - 1000.0).abs() < 1e-6 && normal.len() < 1e-9);
assert!((mom / (4.0 * v6) - centre).len() < 1e-6 * at.len(), "{o:?}");
}
let (_, v6_origin, _, normal) = sums(&open, Vec3::ZERO);
assert!((normal.len() - 0.5).abs() < 1e-9);
// The facet faces the origin: leaving it out adds its cone to the origin, 167 mm³.
assert!((v6_origin / 6.0 - (1000.0 + 0.5 * 1000.0 / 3.0)).abs() < 1e-3, "{}", v6_origin / 6.0);
let (_, v6, mom, _) = sums(&open, centre);
assert!((v6 / 6.0 - (1000.0 - 0.5 * 5.0 / 3.0)).abs() < 1e-6, "{}", v6 / 6.0);
assert!((mom / (4.0 * v6) - centre).len() < 0.01, "{:?}", mom / (4.0 * v6));
}
// A body's measured volume does not depend on where it sits: the same revolved ring of cones
// and cylinders, moved far from the origin, measures what it measures at the origin.
use crate::{revolve, transform};
use solidcraft_geom::{Loop2, Plane, Region2, Vec2};
use std::f64::consts::{PI, TAU};
/// Ring cross-section in (radius, height): cones top and bottom, cylinders inside and out.
const PROFILE: [(f64, f64); 6] = [(5.0, 0.0), (9.0, 0.0), (11.0, 2.0), (11.0, 6.0), (8.0, 8.0), (5.0, 8.0)];
/// Pappus: 2π × the section's first moment about the axis.
fn ring_volume() -> f64 {
let mut moment6 = 0.0;
for (i, &(x0, y0)) in PROFILE.iter().enumerate() {
let (x1, y1) = PROFILE[(i + 1) % PROFILE.len()];
moment6 += (x0 + x1) * (x0 * y1 - x1 * y0);
}
TAU * moment6 / 6.0
}
fn revolved(plane: &Plane, pts: &[Vec2]) -> Body {
let region = Region2 { outer: Loop2::polygon(pts), holes: vec![] };
revolve(plane, &[region], Vec2::ZERO, Vec2::Y, TAU).unwrap().pop().unwrap()
}
fn rel(a: f64, b: f64) -> f64 {
(a - b).abs() / b.abs()
}
#[test]
fn ring_volume_does_not_depend_on_placement() {
let pts: Vec<Vec2> = PROFILE.iter().map(|&(r, z)| Vec2::new(r, z)).collect();
let base = revolved(&Plane::XZ, &pts);
let at_origin = measure(&base).unwrap();
assert!(rel(at_origin.volume, ring_volume()) < 1e-4, "{} vs {}", at_origin.volume, ring_volume());
for d in [100.0, 1000.0, 10000.0] {
for axis in [Vec3::X, Vec3::Y, Vec3::Z, Vec3::new(1.0, 1.0, 1.0)] {
let m = measure(&transform(&base, axis * d, Vec3::ZERO, Vec3::Z, 0.0).unwrap()).unwrap();
assert!(rel(m.volume, at_origin.volume) < 1e-6, "moved {d} along {axis:?}: {} vs {}", m.volume, at_origin.volume);
let off = m.centroid - at_origin.centroid - axis * d;
assert!(off.len() < 1e-6 * d, "centroid moved {d} along {axis:?}: off by {off:?}");
}
}
}
#[test]
fn cylinder_and_cone_volumes_far_from_the_origin() {
let (r, h) = (7.0, 12.0);
// A frustum, radii 7 and 3, height 10: πh/3 (R² + Rr + r²).
let frustum = [Vec2::new(0.0, 0.0), Vec2::new(7.0, 0.0), Vec2::new(3.0, 10.0), Vec2::new(0.0, 10.0)];
let cone_volume = PI * 10.0 / 3.0 * (49.0 + 21.0 + 9.0);
for at in [Vec3::ZERO, Vec3::new(5000.0, -3000.0, 8000.0)] {
let cyl = measure(&cylinder(at, Vec3::Z, r, h).unwrap()).unwrap();
assert!(rel(cyl.volume, PI * r * r * h) < 5e-4, "cylinder at {at:?}: {}", cyl.volume);
let cone = measure(&revolved(&Plane { origin: at, ..Plane::XZ }, &frustum)).unwrap();
assert!(rel(cone.volume, cone_volume) < 5e-4, "frustum at {at:?}: {} vs {cone_volume}", cone.volume);
}
}
}