use crate::common::DistMode;
use crate::metrology::Distance3;
use crate::{Mesh3, Point3, Result, SurfacePoint3, UnitVec3};
use rayon::prelude::*;
const MAX_DEVIATION_SAMPLES: f64 = 5.0e7;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SurfaceDeviation {
pub reference_to_test: f64,
pub test_to_reference: f64,
pub reference_samples: usize,
pub test_samples: usize,
}
impl SurfaceDeviation {
pub fn hausdorff(&self) -> f64 {
self.reference_to_test.max(self.test_to_reference)
}
}
impl std::fmt::Display for SurfaceDeviation {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"ref->test {:.6} ({} samples), test->ref {:.6} ({} samples), hausdorff {:.6}",
self.reference_to_test,
self.reference_samples,
self.test_to_reference,
self.test_samples,
self.hausdorff()
)
}
}
pub(crate) fn derived_spacing(mesh: &Mesh3) -> Result<f64> {
let areas = mesh.compute_face_areas()?;
if areas.is_empty() {
return Err("Cannot derive a sample spacing for a mesh with no faces".into());
}
let mean = areas.iter().sum::<f64>() / areas.len() as f64;
if mean <= 0.0 {
return Err("Cannot derive a sample spacing for a mesh of zero area".into());
}
Ok((mean * 4.0 / 3.0_f64.sqrt()).sqrt() / 4.0)
}
fn check_sample_budget(from: &Mesh3, spacing: f64, label: &str) -> Result<()> {
let areas = from.compute_face_areas()?;
let total: f64 = areas.iter().sum();
let estimate = total / (spacing * spacing);
if estimate > MAX_DEVIATION_SAMPLES {
return Err(format!(
"A spacing of {} would take roughly {:.0} samples on the {} surface, over the limit of \
{:.0}. Use a larger spacing.",
spacing, estimate, label, MAX_DEVIATION_SAMPLES
)
.into());
}
Ok(())
}
fn one_sided(from: &Mesh3, to: &Mesh3, spacing: f64, label: &str) -> Result<(f64, usize)> {
check_sample_budget(from, spacing, label)?;
let samples = from.sample_dense(spacing, None)?;
let worst = samples
.points()
.par_iter()
.map(|p| to.distance_closest_to(p))
.reduce(|| 0.0f64, f64::max);
Ok((worst, samples.point_count()))
}
#[cfg(test)]
pub(crate) fn sample_distances(
from: &Mesh3,
to: &Mesh3,
spacing: f64,
label: &str,
) -> Result<Vec<f64>> {
check_sample_budget(from, spacing, label)?;
Ok(from
.sample_dense(spacing, None)?
.points()
.par_iter()
.map(|p| to.distance_closest_to(p))
.collect())
}
impl Mesh3 {
pub fn measure_surface_deviation(
&self,
test: &Mesh3,
max_spacing: Option<f64>,
) -> Result<SurfaceDeviation> {
if let Some(s) = max_spacing
&& (s.is_nan() || s <= 0.0)
{
return Err(format!("A sample spacing must be positive, got {}", s).into());
}
let reference_spacing = match max_spacing {
Some(s) => s,
None => derived_spacing(self)?,
};
let test_spacing = match max_spacing {
Some(s) => s,
None => derived_spacing(test)?,
};
let (reference_to_test, reference_samples) =
one_sided(self, test, reference_spacing, "reference")?;
let (test_to_reference, test_samples) = one_sided(test, self, test_spacing, "test")?;
Ok(SurfaceDeviation {
reference_to_test,
test_to_reference,
reference_samples,
test_samples,
})
}
}
impl Mesh3 {
pub fn measure_point_deviation(&self, point: &Point3, dist_mode: DistMode) -> Distance3 {
let closest = self.surface_closest_to(point).sp;
let d = deviation_direction(&closest, point, dist_mode);
Distance3::new(closest.point, *point, Some(d))
}
pub fn measure_deviations(&self, points: &[Point3], dist_mode: DistMode) -> Vec<f64> {
points
.iter()
.map(|point| {
let closest = self.surface_closest_to(point).sp;
let d = deviation_direction(&closest, point, dist_mode);
d.dot(&(point - closest.point))
})
.collect()
}
}
fn deviation_direction(closest: &SurfacePoint3, point: &Point3, dist_mode: DistMode) -> UnitVec3 {
match dist_mode {
DistMode::ToPoint => {
let v = point - closest.point;
if v.norm() < 1e-6 {
closest.normal
} else if closest.normal.dot(&v) > 0.0 {
UnitVec3::new_normalize(v)
} else {
-UnitVec3::new_normalize(v)
}
}
DistMode::ToPlane => closest.normal,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::metrology::Measurement;
use approx::assert_relative_eq;
#[test]
fn measure_deviations_matches_the_single_point_measurement() {
let mesh = Mesh3::create_box(2.0, 2.0, 2.0, true);
let points = vec![
Point3::new(0.0, 0.0, 3.0), Point3::new(0.0, 0.0, -3.0), Point3::new(0.0, 0.0, 1.0), Point3::new(5.0, 5.0, 5.0), Point3::new(0.1, -0.2, 0.05), ];
for mode in [DistMode::ToPoint, DistMode::ToPlane] {
let bulk = mesh.measure_deviations(&points, mode);
assert_eq!(bulk.len(), points.len());
for (i, point) in points.iter().enumerate() {
let single = mesh.measure_point_deviation(point, mode).value();
assert_relative_eq!(bulk[i], single, epsilon = 1.0e-15);
}
}
}
#[test]
fn measure_deviations_signs_the_outside_positive() {
let mesh = Mesh3::create_box(2.0, 2.0, 2.0, false);
let values = mesh.measure_deviations(
&[Point3::new(0.0, 0.0, 2.0), Point3::new(0.0, 0.0, 0.5)],
DistMode::ToPoint,
);
assert_relative_eq!(values[0], 1.0, epsilon = 1.0e-12);
assert!(values[1] < 0.0);
}
#[test]
fn measure_deviations_of_nothing_is_nothing() {
let mesh = Mesh3::create_box(1.0, 1.0, 1.0, true);
assert!(mesh.measure_deviations(&[], DistMode::ToPoint).is_empty());
}
#[test]
fn a_mesh_does_not_deviate_from_itself() {
let mesh = Mesh3::create_sphere(10.0, 0.06).unwrap();
let d = mesh.measure_surface_deviation(&mesh, None).unwrap();
assert!(d.hausdorff() < 1.0e-9, "got {}", d);
assert!(d.reference_samples > 0);
assert!(d.test_samples > 0);
}
fn square_at(z: f64) -> Mesh3 {
Mesh3::new(
vec![
Point3::new(-1.0, -1.0, z),
Point3::new(1.0, -1.0, z),
Point3::new(1.0, 1.0, z),
Point3::new(-1.0, 1.0, z),
],
vec![[0u32, 1, 2], [0, 2, 3]],
false,
)
}
#[test]
fn a_uniform_offset_is_measured_in_both_directions() {
let d = square_at(0.0)
.measure_surface_deviation(&square_at(0.25), None)
.unwrap();
assert_relative_eq!(d.reference_to_test, 0.25, epsilon = 1.0e-9);
assert_relative_eq!(d.test_to_reference, 0.25, epsilon = 1.0e-9);
assert_relative_eq!(d.hausdorff(), 0.25, epsilon = 1.0e-9);
}
#[test]
fn the_two_directions_are_reported_separately() {
let small = square_at(0.0);
let large = Mesh3::new(
vec![
Point3::new(-5.0, -5.0, 0.0),
Point3::new(5.0, -5.0, 0.0),
Point3::new(5.0, 5.0, 0.0),
Point3::new(-5.0, 5.0, 0.0),
],
vec![[0u32, 1, 2], [0, 2, 3]],
false,
);
let d = small.measure_surface_deviation(&large, None).unwrap();
assert!(d.reference_to_test < 1.0e-9, "got {}", d);
assert!(d.test_to_reference > 3.0, "got {}", d);
assert_relative_eq!(d.hausdorff(), d.test_to_reference, epsilon = 1.0e-12);
}
#[test]
fn surfaces_agreeing_at_every_vertex_can_still_deviate() {
let corners = vec![
Point3::new(-1.0, -1.0, 1.0),
Point3::new(1.0, -1.0, -1.0),
Point3::new(1.0, 1.0, 1.0),
Point3::new(-1.0, 1.0, -1.0),
];
let up = Mesh3::new(corners.clone(), vec![[0u32, 1, 2], [0, 2, 3]], false);
let down = Mesh3::new(corners, vec![[0u32, 1, 3], [1, 2, 3]], false);
for p in up.points() {
assert!(down.distance_closest_to(p) < 1.0e-9);
}
for p in down.points() {
assert!(up.distance_closest_to(p) < 1.0e-9);
}
let d = up.measure_surface_deviation(&down, None).unwrap();
assert!(
d.hausdorff() > 0.5,
"a vertex-only check would report zero here, got {}",
d
);
}
#[test]
fn an_absurd_spacing_is_refused_rather_than_attempted() {
let mesh = Mesh3::create_sphere(100.0, 0.1).unwrap();
let err = mesh
.measure_surface_deviation(&mesh, Some(1.0e-4))
.unwrap_err();
assert!(
err.to_string().contains("larger spacing"),
"unhelpful message: {}",
err
);
}
#[test]
fn a_nonsense_spacing_is_rejected() {
let mesh = Mesh3::create_box(1.0, 1.0, 1.0, true);
assert!(mesh.measure_surface_deviation(&mesh, Some(0.0)).is_err());
assert!(mesh.measure_surface_deviation(&mesh, Some(-1.0)).is_err());
}
}