use super::{Mesh3, MeshSurfPoint};
use crate::common::PCoords;
use crate::common::barycentric::barycentric;
use crate::geom2::Aabb2;
use crate::raster2::RasterMapping;
use crate::{Iso3, Point2, Point3, Result, SurfacePoint3, Vector2};
use parry2d_f64::partitioning::TraversalAction;
use parry2d_f64::query::{PointQuery, PointQueryWithLocation};
use parry2d_f64::shape::TriMesh;
pub struct FlatDomain<'a> {
mesh: &'a Mesh3,
flat: TriMesh,
}
impl Mesh3 {
pub fn compute_flat_domain(&self) -> Result<FlatDomain<'_>> {
let flat = self.point_flat().ok_or(
"The mesh has no point_flat attribute. Set one with set_point_flat, for example from \
compute_edges()?.boundary_first_flatten()?, before building a flat domain.",
)?;
let flat = TriMesh::new(flat.to_vec(), self.faces().to_vec())?;
Ok(FlatDomain { mesh: self, flat })
}
}
impl<'a> FlatDomain<'a> {
pub fn mesh(&self) -> &'a Mesh3 {
self.mesh
}
pub fn bounds(&self) -> Aabb2 {
self.flat.local_aabb()
}
pub fn flat_at(&self, face_index: u32, bc: [f64; 3]) -> Result<Point2> {
if face_index as usize >= self.mesh.face_count() {
return Err(format!(
"Face index {} is out of range for a mesh with {} faces",
face_index,
self.mesh.face_count()
)
.into());
}
let tri = self.flat.triangle(face_index);
Ok(Point2::from(
tri.a.coords * bc[0] + tri.b.coords * bc[1] + tri.c.coords * bc[2],
))
}
pub fn flat_closest_to(&self, point: &impl PCoords<3>) -> Point2 {
let mp = self.mesh.surface_closest_to(point);
self.flat_at(mp.face_index, mp.bc)
.expect("the closest surface point of a mesh lies on one of its own faces")
}
pub fn project_to_flat(
&self,
point: &impl PCoords<3>,
max_dist: f64,
max_angle: f64,
transform: Option<&Iso3>,
) -> Option<(Point2, f64)> {
let point = Point3::from(point.coords());
let point = transform.map_or(point, |t| t * point);
let (prj, face_index, loc) = self
.mesh
.project_with_tol(&point, max_dist, max_angle, None)?;
let bc = loc.barycentric_coordinates()?;
let normal = self.mesh.shape.triangle(face_index).normal()?;
let flat = self
.flat_at(face_index, bc)
.expect("project_with_tol returns a face index of this mesh");
let depth = SurfacePoint3::new(prj.point, normal).scalar_projection(&point);
Some((flat, depth))
}
pub fn surface_at(&self, flat: &impl PCoords<2>) -> Option<MeshSurfPoint> {
let (face_index, bc) = self.containing_face(&Point2::from(flat.coords()))?;
self.mesh.at_barycentric(face_index, bc).ok()
}
pub fn surface_closest_to(&self, flat: &impl PCoords<2>) -> Result<MeshSurfPoint> {
let p = Point2::from(flat.coords());
let (prj, (face_index, _)) = self.flat.project_local_point_and_get_location(&p, true);
let tri = self.flat.triangle(face_index);
let bc = barycentric(&tri.a, &tri.b, &tri.c, &prj.point);
self.mesh.at_barycentric(face_index, bc)
}
pub fn raster_mapping(&self, px_size: f64, padding: usize) -> RasterMapping {
let bounds = self.bounds();
let size = bounds.maxs - bounds.mins;
let width_px = (size.x / px_size).ceil() as usize + padding * 2;
let height_px = (size.y / px_size).ceil() as usize + padding * 2;
let pad = padding as f64 * px_size;
let origin = bounds.mins - Vector2::new(pad, pad);
RasterMapping::new(origin, (height_px, width_px), px_size, None)
}
fn containing_face(&self, point: &Point2) -> Option<(u32, [f64; 3])> {
let mut result = None;
self.flat.bvh().traverse(|node| {
if !node.aabb().contains_local_point(point) {
return TraversalAction::Prune;
}
if let Some(index) = node.leaf_data() {
let tri = self.flat.triangle(index);
if tri.contains_local_point(point) {
result = Some((index, barycentric(&tri.a, &tri.b, &tri.c, point)));
return TraversalAction::EarlyExit;
}
}
TraversalAction::Continue
});
result
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Vector3;
use crate::common::points::dist;
use approx::assert_relative_eq;
use std::f64::consts::PI;
fn square() -> Mesh3 {
let points = vec![
Point3::new(0.0, 0.0, 0.0),
Point3::new(1.0, 0.0, 0.0),
Point3::new(1.0, 1.0, 0.0),
Point3::new(0.0, 1.0, 0.0),
];
let mut mesh = Mesh3::new(points, vec![[0, 1, 2], [0, 2, 3]], false);
let flat = mesh
.points()
.iter()
.map(|p| Point2::new(p.x, p.y))
.collect();
mesh.set_point_flat(Some(flat)).unwrap();
mesh
}
fn half_cylinder(radius: f64, height: f64, n_theta: usize, n_z: usize) -> Mesh3 {
let mut points = Vec::new();
let mut flat = Vec::new();
for iz in 0..=n_z {
let z = height * iz as f64 / n_z as f64;
for it in 0..=n_theta {
let theta = PI * it as f64 / n_theta as f64;
points.push(Point3::new(radius * theta.cos(), radius * theta.sin(), z));
flat.push(Point2::new(radius * theta, z));
}
}
let row = (n_theta + 1) as u32;
let mut faces = Vec::new();
for iz in 0..n_z as u32 {
for it in 0..n_theta as u32 {
let a = iz * row + it;
let b = a + 1;
let c = a + row;
let d = c + 1;
faces.push([a, b, d]);
faces.push([a, d, c]);
}
}
let mut mesh = Mesh3::new(points, faces, false);
mesh.set_point_flat(Some(flat)).unwrap();
mesh
}
#[test]
fn a_mesh_without_flat_coordinates_has_no_domain() {
let mesh = Mesh3::create_box(1.0, 1.0, 1.0, false);
let message = mesh.compute_flat_domain().err().unwrap().to_string();
assert!(message.contains("point_flat"), "{message}");
}
#[test]
fn flat_at_interpolates_the_chart_and_checks_the_face() -> Result<()> {
let mesh = square();
let domain = mesh.compute_flat_domain()?;
let p = domain.flat_at(0, [1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0])?;
assert_relative_eq!(p, Point2::new(2.0 / 3.0, 1.0 / 3.0), epsilon = 1e-12);
let p = domain.flat_at(1, [0.0, 0.0, 1.0])?;
assert_relative_eq!(p, Point2::new(0.0, 1.0), epsilon = 1e-12);
assert!(domain.flat_at(2, [1.0, 0.0, 0.0]).is_err());
Ok(())
}
#[test]
fn surface_at_finds_the_containing_face_and_misses_outside() -> Result<()> {
let mesh = square();
let domain = mesh.compute_flat_domain()?;
let mp = domain
.surface_at(&Point2::new(2.0 / 3.0, 1.0 / 3.0))
.expect("inside the chart");
assert_eq!(mp.face_index, 0);
for w in mp.bc {
assert_relative_eq!(w, 1.0 / 3.0, epsilon = 1e-9);
}
assert_relative_eq!(
mp.sp.point,
Point3::new(2.0 / 3.0, 1.0 / 3.0, 0.0),
epsilon = 1e-9
);
assert_relative_eq!(mp.sp.normal.into_inner(), Vector3::z(), epsilon = 1e-12);
let mp = domain
.surface_at(&Point2::new(0.25, 0.75))
.expect("inside the chart");
assert_eq!(mp.face_index, 1);
assert_relative_eq!(mp.sp.point, Point3::new(0.25, 0.75, 0.0), epsilon = 1e-9);
assert!(domain.surface_at(&Point2::new(2.0, 2.0)).is_none());
assert!(domain.surface_at(&Point2::new(-0.01, 0.5)).is_none());
Ok(())
}
#[test]
fn surface_closest_to_snaps_outside_points_to_the_chart_boundary() -> Result<()> {
let mesh = square();
let domain = mesh.compute_flat_domain()?;
let mp = domain.surface_closest_to(&Point2::new(1.5, 0.5))?;
assert_relative_eq!(mp.sp.point, Point3::new(1.0, 0.5, 0.0), epsilon = 1e-9);
let snapped = domain.flat_at(mp.face_index, mp.bc)?;
assert_relative_eq!(snapped, Point2::new(1.0, 0.5), epsilon = 1e-9);
let inside = Point2::new(0.3, 0.2);
let a = domain.surface_closest_to(&inside)?;
let b = domain.surface_at(&inside).unwrap();
assert_eq!(a.face_index, b.face_index);
assert_relative_eq!(a.sp.point, b.sp.point, epsilon = 1e-9);
Ok(())
}
#[test]
fn project_to_flat_reports_depth_and_honors_the_tolerances() -> Result<()> {
let mesh = square();
let domain = mesh.compute_flat_domain()?;
let above = Point3::new(0.6, 0.2, 0.05);
let (flat, depth) = domain
.project_to_flat(&above, 0.1, PI / 4.0, None)
.expect("within tolerance");
assert_relative_eq!(flat, Point2::new(0.6, 0.2), epsilon = 1e-9);
assert_relative_eq!(depth, 0.05, epsilon = 1e-12);
let below = Point3::new(0.6, 0.2, -0.05);
let (_, depth) = domain.project_to_flat(&below, 0.1, PI / 4.0, None).unwrap();
assert_relative_eq!(depth, -0.05, epsilon = 1e-12);
assert!(
domain
.project_to_flat(&Point3::new(0.6, 0.2, 0.5), 0.1, PI / 4.0, None)
.is_none()
);
assert!(
domain
.project_to_flat(&Point3::new(1.05, 0.5, 0.0), 0.1, PI / 4.0, None)
.is_none()
);
let shift = Iso3::translation(0.0, 0.0, -0.05);
let (_, depth) = domain
.project_to_flat(&above, 0.1, PI / 4.0, Some(&shift))
.unwrap();
assert_relative_eq!(depth, 0.0, epsilon = 1e-12);
let far = domain.flat_closest_to(&Point3::new(0.6, 0.2, 5.0));
assert_relative_eq!(far, Point2::new(0.6, 0.2), epsilon = 1e-9);
Ok(())
}
#[test]
fn a_half_cylinder_round_trips_through_its_unrolled_chart() -> Result<()> {
let radius = 10.0;
let mesh = half_cylinder(radius, 20.0, 36, 8);
let domain = mesh.compute_flat_domain()?;
for (theta, z, offset) in [
(0.3, 5.0, 0.2),
(1.2, 12.5, -0.15),
(2.0, 1.0, 0.05),
(2.9, 18.0, 0.3),
] {
let p = Point3::new(
(radius + offset) * f64::cos(theta),
(radius + offset) * f64::sin(theta),
z,
);
let (flat, depth) = domain
.project_to_flat(&p, 1.0, PI / 4.0, None)
.expect("close to the wall");
assert!(
(depth - offset).abs() < 0.05,
"theta {theta}: depth {depth} vs offset {offset}"
);
assert!(
(flat.x - radius * theta).abs() < 0.05 && (flat.y - z).abs() < 1e-9,
"theta {theta}: flat {flat:?}"
);
let back = domain.surface_at(&flat).expect("inside the chart");
let foot = mesh.surface_closest_to(&p);
assert!(dist(&back.sp.point, &foot.sp.point) < 1e-9);
}
let bounds = domain.bounds();
assert_relative_eq!(bounds.mins, Point2::new(0.0, 0.0), epsilon = 1e-12);
assert_relative_eq!(bounds.maxs, Point2::new(radius * PI, 20.0), epsilon = 1e-12);
Ok(())
}
#[test]
fn raster_mapping_covers_the_chart_with_padding() -> Result<()> {
let mesh = square();
let domain = mesh.compute_flat_domain()?;
let mapping = domain.raster_mapping(0.25, 2);
assert_eq!(mapping.shape(), (8, 8));
assert_relative_eq!(mapping.origin(), Point2::new(-0.5, -0.5), epsilon = 1e-12);
assert_relative_eq!(mapping.px_size(), 0.25, epsilon = 0.0);
Ok(())
}
}