mod collisions;
mod conformal;
mod edges;
pub mod filtering;
pub mod half_edge;
mod measurement;
mod nav_structure;
mod outline;
mod queries;
pub mod sampling;
mod section;
mod uv_mapping;
use crate::common::{IndexMask, PCoords};
use crate::geom3::IsoExtensions3;
use crate::io::{deflate_bytes, u_bytes_to_mesh};
use crate::na::SVector;
use crate::{Iso3, Point2, Point3, Result, SurfacePoint3, UnitVec3, Vector3};
pub use collisions::MeshCollisionSet;
pub use edges::MeshEdges;
pub use half_edge::HalfEdgeMesh;
pub use nav_structure::MeshNav;
use parry3d_f64::bounding_volume::Aabb;
use parry3d_f64::shape::{TriMesh, TriMeshFlags};
use parry3d_f64::{shape, transformation};
pub use uv_mapping::UvMapping;
#[derive(Debug, Clone, Copy)]
pub struct MeshSurfPoint {
pub face_index: u32,
pub bc: [f64; 3],
pub sp: SurfacePoint3,
}
impl MeshSurfPoint {
pub fn new(face_index: u32, bc: [f64; 3], sp: SurfacePoint3) -> Self {
Self { face_index, bc, sp }
}
pub fn point(&self) -> Point3 {
self.sp.point
}
pub fn normal(&self) -> UnitVec3 {
self.sp.normal
}
pub fn new_transformed_by(&self, iso: &Iso3) -> Self {
Self {
face_index: self.face_index,
bc: self.bc,
sp: iso * self.sp,
}
}
}
impl Default for MeshSurfPoint {
fn default() -> Self {
Self {
face_index: 0,
bc: [0.0, 0.0, 0.0],
sp: SurfacePoint3::default(),
}
}
}
impl PCoords<3> for MeshSurfPoint {
fn coords(&self) -> SVector<f64, 3> {
self.sp.point.coords
}
}
#[derive(Clone)]
pub struct Mesh {
shape: TriMesh,
is_solid: bool,
uv: Option<UvMapping>,
}
impl Mesh {
pub fn aabb(&self) -> Aabb {
self.shape.local_aabb()
}
pub fn tri_mesh(&self) -> &TriMesh {
&self.shape
}
pub fn is_solid(&self) -> bool {
self.is_solid
}
pub fn vertices(&self) -> &[Point3] {
self.shape.vertices()
}
pub fn faces(&self) -> &[[u32; 3]] {
self.shape.indices()
}
}
impl Mesh {
pub fn new_with_options(
vertices: Vec<Point3>,
triangles: Vec<[u32; 3]>,
is_solid: bool,
merge_duplicates: bool,
delete_degenerate: bool,
uv: Option<Vec<Point2>>,
) -> Result<Self> {
let mut flags = TriMeshFlags::empty();
if merge_duplicates {
flags |= TriMeshFlags::MERGE_DUPLICATE_VERTICES;
flags |= TriMeshFlags::DELETE_DUPLICATE_TRIANGLES;
}
if delete_degenerate {
flags |= TriMeshFlags::DELETE_BAD_TOPOLOGY_TRIANGLES;
flags |= TriMeshFlags::DELETE_DEGENERATE_TRIANGLES;
}
let uv_mapping = if let Some(uv) = uv {
Some(UvMapping::new(uv, triangles.clone())?)
} else {
None
};
let shape = TriMesh::with_flags(vertices, triangles, flags)?;
Ok(Self {
shape,
is_solid,
uv: uv_mapping,
})
}
pub fn new(vertices: Vec<Point3>, triangles: Vec<[u32; 3]>, is_solid: bool) -> Self {
let shape = TriMesh::new(vertices, triangles).expect("Failed to create TriMesh");
Self {
shape,
is_solid,
uv: None,
}
}
pub fn new_take_trimesh(shape: TriMesh, is_solid: bool) -> Self {
Self {
shape,
is_solid,
uv: None,
}
}
}
impl Mesh {
pub fn transform_by(&mut self, transform: &Iso3) {
self.shape.transform_vertices(transform);
}
pub fn new_transformed_by(&self, transform: &Iso3) -> Self {
let mut result = self.clone();
result.transform_by(transform);
result
}
pub fn new_scaled_uniform(&self, scale: f64) -> Self {
let new_shape = self
.shape
.clone()
.scaled(&Vector3::new(scale, scale, scale));
Mesh::new_take_trimesh(new_shape, self.is_solid)
}
pub fn new_offset_vertices(&self, offset: f64) -> Self {
let normals = self.get_vertex_normals();
let updated = self
.vertices()
.iter()
.zip(normals.iter())
.map(|(v, n)| v + offset * n)
.collect();
Self::new(updated, self.faces().to_vec(), self.is_solid)
}
}
impl Mesh {
pub fn calc_edges(&self) -> Result<MeshEdges<'_>> {
MeshEdges::new(self)
}
pub fn convex_hull(&self) -> Self {
let (vertices, faces) = transformation::convex_hull(self.shape.vertices());
Self::new(vertices, faces, true)
}
pub fn append(&mut self, other: &Mesh) -> Result<()> {
if self.uv.is_some() || other.uv.is_some() {
return Err("Cannot append meshes with UV mappings".into());
}
self.shape.append(&other.shape);
Ok(())
}
pub fn uv(&self) -> Option<&UvMapping> {
self.uv.as_ref()
}
pub fn uv_to_3d(&self, uv: &Point2) -> Option<MeshSurfPoint> {
let (i, bc) = self.uv()?.triangle(uv)?;
self.at_barycentric(i, bc).ok()
}
pub fn project_to_uv(&self, p: &impl PCoords<3>) -> Option<Point2> {
let uv_map = self.uv()?;
let mp = self.surf_closest_to(p);
Some(uv_map.point(mp.face_index, mp.bc))
}
pub fn uv_with_tol(
&self,
point: &Point3,
max_dist: f64,
max_angle: f64,
transform: Option<&Iso3>,
) -> Option<(Point2, f64)> {
if let Some(uv_map) = self.uv() {
let point = if let Some(transform) = transform {
transform * point
} else {
*point
};
if let Some((prj, id, loc)) = self.project_with_tol(&point, max_dist, max_angle, None) {
let triangle = self.shape.triangle(id);
if let Some(normal) = triangle.normal() {
let uv = uv_map.point(id, loc.barycentric_coordinates().unwrap());
let sp = SurfacePoint3::new(prj.point, normal);
Some((uv, sp.scalar_projection(&point)))
} else {
None
}
} else {
None
}
} else {
None
}
}
pub fn nav(&self) -> MeshNav<'_> {
MeshNav::new(self)
}
pub fn get_patches(&self, mask: Option<&IndexMask>) -> Result<Vec<IndexMask>> {
let nav = self.nav();
nav.patches(mask)
}
pub fn get_patch_boundary_points(&self) -> Result<Vec<Vec<Point3>>> {
let edges = MeshEdges::new(self)?;
let mut b_loops = Vec::new();
for b_loop in edges.boundary_loops.iter() {
b_loops.push(
b_loop
.iter()
.map(|vi| self.vertices()[*vi as usize])
.collect(),
);
}
Ok(b_loops)
}
pub fn get_face_normals(&self) -> Result<Vec<UnitVec3>> {
let mut result = Vec::new();
for t in self.shape.triangles() {
if let Some(n) = t.normal() {
result.push(n);
} else {
return Err("Failed to get normal".into());
}
}
Ok(result)
}
pub fn get_face_areas(&self) -> Vec<f64> {
self.shape.triangles().map(|t| t.area()).collect::<Vec<_>>()
}
pub fn get_face_centers(&self) -> Vec<Point3> {
self.shape
.triangles()
.map(|t| t.center())
.collect::<Vec<_>>()
}
pub fn get_vertex_normals(&self) -> Vec<Vector3> {
let mut sums: Vec<Vector3> = vec![Vector3::new(0.0, 0.0, 0.0); self.shape.vertices().len()];
let mut weights = vec![0.0; self.shape.vertices().len()];
for (face_i, tri) in self.shape.triangles().enumerate() {
let indices = self.shape.indices()[face_i];
let a = tri.area();
if let Some(n) = tri.normal() {
for i in indices {
sums[i as usize] += n.into_inner() * a;
weights[i as usize] += a;
}
}
}
for i in 0..sums.len() {
if weights[i] > 0.0 {
let v = sums[i] / weights[i];
sums[i] = v.normalize();
}
}
sums
}
}
impl Mesh {
pub fn create_cone(half_height: f64, radius: f64, steps: usize) -> Self {
let cone = shape::Cone::new(half_height, radius);
let (vertices, faces) = cone.to_trimesh(steps as u32);
Self::new(vertices, faces, true)
}
pub fn create_capsule(
p0: &Point3,
p1: &Point3,
radius: f64,
n_theta: usize,
n_phi: usize,
) -> Self {
let capsule = shape::Capsule::new(*p0, *p1, radius);
let (vertices, faces) = capsule.to_trimesh(n_theta as u32, n_phi as u32);
Self::new(vertices, faces, true)
}
pub fn create_sphere(radius: f64, n_theta: usize, n_phi: usize) -> Self {
let sphere = shape::Ball::new(radius);
let (vertices, faces) = sphere.to_trimesh(n_theta as u32, n_phi as u32);
Self::new(vertices, faces, true)
}
pub fn create_box(length: f64, width: f64, height: f64, is_solid: bool) -> Self {
let bx = shape::Cuboid::new(Vector3::new(length / 2.0, width / 2.0, height / 2.0));
let (vertices, triangles) = bx.to_trimesh();
Self::new(vertices, triangles, is_solid)
}
pub fn create_cylinder(radius: f64, height: f64, steps: usize) -> Self {
let cyl = shape::Cylinder::new(height / 2.0, radius);
let (vertices, faces) = cyl.to_trimesh(steps as u32);
Self::new(vertices, faces, true)
}
pub fn create_rect_beam_between(
p0: &Point3,
p1: &Point3,
width: f64,
height: f64,
up: &Vector3,
) -> Result<Self> {
let v = *p1 - *p0;
let pc = *p0 + v / 2.0;
let box_geom = shape::Cuboid::new(Vector3::new(width / 2.0, height / 2.0, v.norm() / 2.0));
let transform = Iso3::try_from_basis_zy(&v, up, Some(pc))?;
let (vertices, faces) = box_geom.to_trimesh();
let mut mesh = Self::new(vertices, faces, true);
mesh.transform_by(&transform);
Ok(mesh)
}
pub fn create_cylinder_between(p0: &Point3, p1: &Point3, radius: f64, steps: usize) -> Self {
let v = *p1 - *p0;
let pc = *p0 + v / 2.0;
let cyl = shape::Cylinder::new(v.norm() / 2.0, radius);
let transform = Iso3::try_from_basis_yz(&v, &Vector3::z(), Some(pc))
.unwrap_or(Iso3::try_from_basis_yx(&v, &Vector3::x(), Some(pc)).unwrap());
let (vertices, faces) = cyl.to_trimesh(steps as u32);
let mut mesh = Self::new(vertices, faces, true);
mesh.transform_by(&transform);
mesh
}
pub fn create_circle(radius: f64, segments: usize) -> Self {
use std::f64::consts::TAU;
let mut vertices = Vec::with_capacity(segments + 1);
let mut faces = Vec::with_capacity(segments);
vertices.push(Point3::origin());
for i in 0..segments {
let angle = TAU * (i as f64) / (segments as f64);
vertices.push(Point3::new(radius * angle.cos(), radius * angle.sin(), 0.0));
}
for i in 0..segments {
let a = (i + 1) as u32;
let b = ((i + 1) % segments + 1) as u32;
faces.push([0u32, a, b]);
}
Self::new(vertices, faces, false)
}
pub fn stanford_bunny_res4() -> Self {
let bytes = include_bytes!("../../tests/data/stanford_bun_4.umesh.gz");
u_bytes_to_mesh(&deflate_bytes(bytes).unwrap()).unwrap()
}
pub fn stanford_bunny_res3() -> Self {
let bytes = include_bytes!("../../tests/data/stanford_bun_3.umesh.gz");
u_bytes_to_mesh(&deflate_bytes(bytes).unwrap()).unwrap()
}
pub fn stanford_bunny_res2() -> Self {
let bytes = include_bytes!("../../tests/data/stanford_bun_2.umesh.gz");
u_bytes_to_mesh(&deflate_bytes(bytes).unwrap()).unwrap()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tests::stanford_bun_4;
use approx::assert_relative_eq;
#[test]
fn vertex_normals_match_vertex_count_and_are_normalized() {
let mesh = stanford_bun_4();
let normals = mesh.get_vertex_normals();
assert_eq!(normals.len(), mesh.vertices().len());
for normal in normals {
assert_relative_eq!(normal.norm(), 1.0, epsilon = 1.0e-12);
}
}
#[test]
fn new_scaled_uniform_scales_spherical_radius() {
let radius = 1.0;
let scale = 2.5;
let mesh = Mesh::create_sphere(radius, 100, 100);
let scaled = mesh.new_scaled_uniform(scale);
assert_eq!(mesh.vertices().len(), scaled.vertices().len());
for vertex in scaled.vertices() {
assert_relative_eq!(vertex.coords.norm(), radius * scale, epsilon = 1.0e-12);
}
}
#[test]
fn new_offset_vertices_preserves_spherical_radius() {
let radius = 1.0;
let offset = 0.1;
let mesh = Mesh::create_sphere(radius, 100, 100);
let offset_mesh = mesh.new_offset_vertices(offset);
assert_eq!(mesh.vertices().len(), offset_mesh.vertices().len());
for vertex in offset_mesh.vertices() {
assert_relative_eq!(vertex.coords.norm(), radius + offset, epsilon = 1.0e-5);
}
}
}