mod data;
mod normal_estimation;
use crate::common::kd_tree::KdTreeSearch;
use crate::common::points::dist;
use crate::{KdTree3, Mesh3, Point3, Result};
pub use data::{PointCloud3, VOXEL_COHERENCE_ATTR, VOXEL_COUNT_ATTR};
pub use normal_estimation::NormalEstimates;
pub trait PointCloudOverlap<TOther> {
fn overlap_by_reciprocity(&self, other: &TOther, max_distance: f64) -> Vec<usize>;
}
pub struct CloudIndex3<'a> {
cloud: &'a PointCloud3,
tree: TreeRef<'a>,
}
enum TreeRef<'a> {
Owned(KdTree3),
Borrowed(&'a KdTree3),
}
impl TreeRef<'_> {
fn get(&self) -> &KdTree3 {
match self {
TreeRef::Owned(tree) => tree,
TreeRef::Borrowed(tree) => tree,
}
}
}
impl<'a> CloudIndex3<'a> {
pub fn try_new(cloud: &'a PointCloud3) -> Result<Self> {
let tree = KdTree3::try_new(cloud.points())?;
Ok(Self {
cloud,
tree: TreeRef::Owned(tree),
})
}
pub(crate) fn with_tree_unchecked(cloud: &'a PointCloud3, tree: &'a KdTree3) -> Self {
Self {
cloud,
tree: TreeRef::Borrowed(tree),
}
}
pub fn cloud(&self) -> &'a PointCloud3 {
self.cloud
}
pub fn tree(&self) -> &KdTree3 {
self.tree.get()
}
pub fn points(&self) -> &[Point3] {
self.cloud.points()
}
pub fn estimate_normals(
&self,
must_match: &[crate::Vector3],
radius: f64,
) -> Result<NormalEstimates> {
if must_match.len() != self.points().len() {
return Err(format!(
"must_match has {} entries but the cloud has {} points",
must_match.len(),
self.points().len()
)
.into());
}
Ok(normal_estimation::estimate_by_neighborhood(
self.points(),
must_match,
self.tree.get(),
radius,
))
}
}
impl KdTreeSearch<3> for CloudIndex3<'_> {
fn nearest_one(&self, point: &impl crate::common::PCoords<3>) -> (usize, f64) {
self.tree.get().nearest_one(point)
}
fn nearest(&self, point: &impl crate::common::PCoords<3>, count: usize) -> Vec<(usize, f64)> {
self.tree.get().nearest(point, count)
}
fn within(&self, point: &impl crate::common::PCoords<3>, radius: f64) -> Vec<(usize, f64)> {
self.tree.get().within(point, radius)
}
fn len(&self) -> usize {
self.tree.get().len()
}
}
impl PointCloudOverlap<Mesh3> for CloudIndex3<'_> {
fn overlap_by_reciprocity(&self, mesh: &Mesh3, max_distance: f64) -> Vec<usize> {
let mut result = Vec::new();
for (i, p_this) in self.points().iter().enumerate() {
let p_other = mesh.point_closest_to(p_this);
let (k, _) = self.tree.get().nearest_one(&p_other);
let p_recip = self.points()[k];
if dist(p_this, &p_recip) < max_distance {
result.push(i);
}
}
result
}
}
impl PointCloudOverlap<CloudIndex3<'_>> for CloudIndex3<'_> {
fn overlap_by_reciprocity(&self, other: &CloudIndex3, max_distance: f64) -> Vec<usize> {
let mut result = Vec::new();
for (i, p_this) in self.points().iter().enumerate() {
let (j, _) = other.tree.get().nearest_one(p_this);
let p_other = other.points()[j];
let (k, _) = self.tree.get().nearest_one(&p_other);
let p_recip = self.points()[k];
if dist(p_this, &p_recip) < max_distance {
result.push(i);
}
}
result
}
}