use crate::common::IndexMask;
use crate::common::poisson_disk::sample_poisson_disk_all;
use crate::common::{VoxelGroups, compute_voxel_groups};
use crate::geom3::Aabb3;
use crate::geom3::attributes3::{Attr3, PointAttrSet3};
use crate::geom3::point_cloud::CloudIndex3;
use crate::{Iso3, KdTree3, Point2, Point3, Result, SurfacePoint3, UnitVec3, Vector3};
use std::fmt;
#[cfg(feature = "ply")]
use crate::io::{PlyWriteOpts, load_ply_points, write_ply_points};
#[cfg(feature = "ply")]
use std::path::Path;
#[derive(Clone, PartialEq)]
pub struct PointCloud3 {
points: Vec<Point3>,
attrs: PointAttrSet3,
}
impl PointCloud3 {
pub fn new(points: Vec<Point3>) -> Self {
Self {
points,
attrs: PointAttrSet3::empty(),
}
}
pub fn new_with_attrs(points: Vec<Point3>, attrs: PointAttrSet3) -> Result<Self> {
attrs.validate(points.len())?;
Ok(Self { points, attrs })
}
pub fn empty() -> Self {
Self::new(Vec::new())
}
pub fn from_surface_points(points: &[SurfacePoint3]) -> Self {
let normals: Vec<UnitVec3> = points.iter().map(|p| p.normal).collect();
let mut attrs = PointAttrSet3::empty();
attrs
.set_normals(Some(normals), points.len())
.expect("one normal per point by construction");
Self {
points: points.iter().map(|p| p.point).collect(),
attrs,
}
}
pub fn compute_index(&self) -> Result<CloudIndex3<'_>> {
CloudIndex3::try_new(self)
}
pub fn index_with_tree_unchecked<'a>(&'a self, tree: &'a KdTree3) -> CloudIndex3<'a> {
CloudIndex3::with_tree_unchecked(self, tree)
}
pub fn sample_poisson_disk(&self, radius: f64) -> IndexMask {
sample_poisson_disk_all(self.points(), radius)
}
pub fn extract_poisson_sample(&self, radius: f64) -> Result<Self> {
let mask = self.sample_poisson_disk(radius);
self.extract_subset_points(&mask)
}
pub fn into_parts(self) -> (Vec<Point3>, PointAttrSet3) {
(self.points, self.attrs)
}
}
impl PointCloud3 {
#[cfg(feature = "ply")]
pub fn load_ply(path: &Path) -> Result<Self> {
let (points, attrs, has_faces) = load_ply_points(path)?;
if has_faces {
return Err(format!(
"The PLY file at {} declares faces, so it is a mesh rather than a point cloud. \
Loading it here would discard the connectivity; use MeshData3::load_ply instead.",
path.display()
)
.into());
}
Ok(Self { points, attrs })
}
#[cfg(feature = "ply")]
pub fn save_ply(&self, path: &Path, opts: &PlyWriteOpts) -> Result<()> {
write_ply_points(path, &self.points, &self.attrs, opts)
}
pub fn check_attribute_loss(&self, format: &str, allow_loss: bool) -> Result<()> {
if allow_loss || self.attrs.is_empty() {
return Ok(());
}
Err(format!(
"Writing to {} would discard the attributes on this point cloud ({}), because the \
format cannot represent them. Set `allow_attribute_loss` to accept this.",
format,
self.attrs.attr_labels().join(", ")
)
.into())
}
}
impl PointCloud3 {
pub fn points(&self) -> &[Point3] {
&self.points
}
pub fn points_mut(&mut self) -> &mut [Point3] {
&mut self.points
}
pub fn point_count(&self) -> usize {
self.points.len()
}
pub fn is_empty(&self) -> bool {
self.points.is_empty()
}
pub fn attrs(&self) -> &PointAttrSet3 {
&self.attrs
}
pub fn compute_aabb(&self) -> Aabb3 {
Aabb3::from_points(self.points.clone())
}
}
impl PointCloud3 {
pub fn point_normals(&self) -> Option<&[UnitVec3]> {
self.attrs.normals()
}
pub fn point_colors(&self) -> Option<&[[u8; 3]]> {
self.attrs.colors()
}
pub fn point_stdev(&self) -> Option<&[f64]> {
self.attrs.stdev()
}
pub fn point_flat(&self) -> Option<&[Point2]> {
self.attrs.flat()
}
pub fn point_attr(&self, name: &str) -> Option<&Attr3> {
self.attrs.attr(name)
}
}
impl PointCloud3 {
pub fn set_point_normals(&mut self, values: Option<Vec<UnitVec3>>) -> Result<()> {
self.attrs.set_normals(values, self.points.len())
}
pub fn set_point_colors(&mut self, values: Option<Vec<[u8; 3]>>) -> Result<()> {
self.attrs.set_colors(values, self.points.len())
}
pub fn set_point_stdev(&mut self, values: Option<Vec<f64>>) -> Result<()> {
self.attrs.set_stdev(values, self.points.len())
}
pub fn set_point_flat(&mut self, values: Option<Vec<Point2>>) -> Result<()> {
self.attrs.set_flat(values, self.points.len())
}
pub fn insert_point_attr(&mut self, name: &str, attr: Attr3) -> Result<()> {
self.attrs.insert_attr(name, attr, self.points.len())
}
pub fn remove_point_attr(&mut self, name: &str) -> Option<Attr3> {
self.attrs.remove_attr(name)
}
pub fn set_attrs(&mut self, attrs: PointAttrSet3) -> Result<()> {
attrs.validate(self.points.len())?;
self.attrs = attrs;
Ok(())
}
pub fn take_attrs(&mut self) -> PointAttrSet3 {
std::mem::take(&mut self.attrs)
}
}
impl PointCloud3 {
pub fn transform_in_place(&mut self, iso: &Iso3) {
for p in self.points.iter_mut() {
*p = iso * *p;
}
self.attrs.transform_in_place(iso);
}
pub fn transform_copy(&self, iso: &Iso3) -> Self {
let mut result = self.clone();
result.transform_in_place(iso);
result
}
pub fn scale_in_place(&mut self, scale: f64) -> Result<()> {
if !scale.is_finite() || scale == 0.0 {
return Err(format!(
"A scale factor must be finite and non-zero, but {scale} was given. Scaling by \
zero would collapse the cloud to a point irrecoverably."
)
.into());
}
for p in self.points.iter_mut() {
*p = Point3::from(p.coords * scale);
}
self.attrs.scale_in_place(scale);
if scale < 0.0 {
self.attrs.flip_in_place();
}
Ok(())
}
pub fn scale_copy(&self, scale: f64) -> Result<Self> {
let mut result = self.clone();
result.scale_in_place(scale)?;
Ok(result)
}
pub fn append_in_place(&mut self, other: &PointCloud3) -> Result<()> {
self.attrs.extend_from(&other.attrs)?;
self.points.extend_from_slice(&other.points);
Ok(())
}
}
impl PointCloud3 {
pub fn extract_subset_points(&self, mask: &IndexMask) -> Result<Self> {
if mask.len() != self.points.len() {
return Err(format!(
"The mask has {} entries, but the cloud has {} points",
mask.len(),
self.points.len()
)
.into());
}
Ok(Self {
points: mask.clone_indices_of(&self.points)?,
attrs: self.attrs.subset(mask)?,
})
}
pub fn extract_subset_indices(&self, indices: &[usize]) -> Result<Self> {
let n = self.points.len();
if let Some(bad) = indices.iter().find(|&&i| i >= n) {
return Err(format!("Index {bad} is out of bounds for a cloud with {n} points").into());
}
Ok(Self {
points: indices.iter().map(|&i| self.points[i]).collect(),
attrs: self.attrs.subset_indices(indices)?,
})
}
}
pub const VOXEL_COHERENCE_ATTR: &str = "voxel_coherence";
pub const VOXEL_COUNT_ATTR: &str = "voxel_count";
impl PointCloud3 {
pub fn reduce_by_voxel(&self, voxel_size: f64) -> Result<Self> {
for name in [VOXEL_COHERENCE_ATTR, VOXEL_COUNT_ATTR] {
if self.attrs.attr(name).is_some() {
return Err(format!(
"The cloud already has an attribute named '{name}', which the reduction would \
overwrite. Remove it first if it is no longer wanted."
)
.into());
}
}
let groups = compute_voxel_groups(&self.points, voxel_size)?;
let n_out = groups.len();
let mut points = Vec::with_capacity(n_out);
let mut counts = Vec::with_capacity(n_out);
for g in groups.iter() {
let mut sum = Vector3::zeros();
for &i in g {
sum += self.points[i as usize].coords;
}
points.push(Point3::from(sum / g.len() as f64));
counts.push(g.len() as u32);
}
let mut attrs = PointAttrSet3::empty();
if let Some(normals) = self.attrs.normals() {
let mut reduced = Vec::with_capacity(n_out);
let mut coherence = Vec::with_capacity(n_out);
for g in groups.iter() {
let mut sum = Vector3::zeros();
for &i in g {
sum += normals[i as usize].into_inner();
}
let mean = sum / g.len() as f64;
let length = mean.norm();
coherence.push(length.min(1.0));
reduced.push(if length > 1e-12 {
UnitVec3::new_unchecked(mean / length)
} else {
normals[g[0] as usize]
});
}
attrs.set_normals(Some(reduced), n_out)?;
attrs.insert_attr(VOXEL_COHERENCE_ATTR, Attr3::Scalar(coherence), n_out)?;
}
if let Some(stdev) = self.attrs.stdev() {
let reduced = groups
.iter()
.map(|g| {
let sum_sq: f64 = g
.iter()
.map(|&i| stdev[i as usize] * stdev[i as usize])
.sum();
sum_sq.sqrt() / g.len() as f64
})
.collect();
attrs.set_stdev(Some(reduced), n_out)?;
}
if let Some(colors) = self.attrs.colors() {
let reduced = groups
.iter()
.map(|g| mean_color(g.iter().map(|&i| colors[i as usize])))
.collect();
attrs.set_colors(Some(reduced), n_out)?;
}
for name in self
.attrs
.attr_names()
.map(str::to_string)
.collect::<Vec<_>>()
{
let attr = self
.attrs
.attr(&name)
.expect("the name came from this attribute set");
attrs.insert_attr(&name, reduce_attr(attr, &groups), n_out)?;
}
attrs.insert_attr(VOXEL_COUNT_ATTR, Attr3::Label(counts), n_out)?;
Ok(Self { points, attrs })
}
}
fn mean_color(colors: impl Iterator<Item = [u8; 3]>) -> [u8; 3] {
let mut sums = [0u32; 3];
let mut n = 0u32;
for c in colors {
for (s, v) in sums.iter_mut().zip(c.iter()) {
*s += u32::from(*v);
}
n += 1;
}
let mut out = [0u8; 3];
for (o, s) in out.iter_mut().zip(sums.iter()) {
*o = ((*s + n / 2) / n) as u8;
}
out
}
fn reduce_attr(attr: &Attr3, groups: &VoxelGroups) -> Attr3 {
match attr {
Attr3::Scalar(values) => Attr3::Scalar(
groups
.iter()
.map(|g| g.iter().map(|&i| values[i as usize]).sum::<f64>() / g.len() as f64)
.collect(),
),
Attr3::Vector(values) => Attr3::Vector(
groups
.iter()
.map(|g| {
let sum: Vector3 = g.iter().map(|&i| values[i as usize]).sum();
sum / g.len() as f64
})
.collect(),
),
Attr3::Color(values) => Attr3::Color(
groups
.iter()
.map(|g| mean_color(g.iter().map(|&i| values[i as usize])))
.collect(),
),
Attr3::Label(values) => Attr3::Label(
groups
.iter()
.map(|g| modal_label(g.iter().map(|&i| values[i as usize])))
.collect(),
),
}
}
fn modal_label(labels: impl Iterator<Item = u32>) -> u32 {
let mut sorted: Vec<u32> = labels.collect();
sorted.sort_unstable();
let mut best = sorted[0];
let mut best_count = 0usize;
let mut current = sorted[0];
let mut count = 0usize;
for v in sorted {
if v == current {
count += 1;
} else {
current = v;
count = 1;
}
if count > best_count {
best = current;
best_count = count;
}
}
best
}
impl fmt::Debug for PointCloud3 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("PointCloud3")
.field("points", &self.points.len())
.field("attrs", &self.attrs)
.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Vector3;
use crate::common::kd_tree::KdTreeSearch;
use approx::assert_relative_eq;
use std::f64::consts::FRAC_PI_2;
fn loaded_cloud() -> PointCloud3 {
let mut cloud = PointCloud3::new(vec![
Point3::new(0.0, 0.0, 0.0),
Point3::new(1.0, 0.0, 0.0),
Point3::new(0.0, 1.0, 0.0),
Point3::new(0.0, 0.0, 1.0),
]);
cloud
.set_point_normals(Some(vec![UnitVec3::new_normalize(Vector3::z()); 4]))
.unwrap();
cloud
.set_point_colors(Some(vec![[0, 0, 0], [1, 1, 1], [2, 2, 2], [3, 3, 3]]))
.unwrap();
cloud
.set_point_stdev(Some(vec![0.1, 0.2, 0.3, 0.4]))
.unwrap();
cloud
.insert_point_attr("confidence", Attr3::Scalar(vec![0.5, 0.6, 0.7, 0.8]))
.unwrap();
cloud
.insert_point_attr("principal_dir", Attr3::Vector(vec![Vector3::x(); 4]))
.unwrap();
cloud
}
#[test]
fn a_bare_cloud_has_no_attributes() {
let cloud = PointCloud3::new(vec![Point3::origin()]);
assert_eq!(cloud.point_count(), 1);
assert!(!cloud.is_empty());
assert!(cloud.attrs().is_empty());
assert!(cloud.point_normals().is_none());
}
#[test]
fn an_empty_cloud_is_legal() {
let cloud = PointCloud3::empty();
assert!(cloud.is_empty());
assert_eq!(cloud.point_count(), 0);
}
#[test]
fn new_with_attrs_rejects_a_mismatched_attribute() {
let mut attrs = PointAttrSet3::empty();
attrs.set_stdev(Some(vec![0.1]), 1).unwrap();
assert!(PointCloud3::new_with_attrs(vec![Point3::origin(); 4], attrs).is_err());
}
#[test]
fn attribute_setters_supply_the_count() -> Result<()> {
let mut cloud = loaded_cloud();
assert_eq!(cloud.point_stdev().unwrap(), &[0.1, 0.2, 0.3, 0.4]);
assert_eq!(cloud.point_attr("confidence").unwrap().len(), 4);
assert!(cloud.set_point_stdev(Some(vec![0.1, 0.2])).is_err());
assert_eq!(cloud.point_stdev().unwrap(), &[0.1, 0.2, 0.3, 0.4]);
Ok(())
}
#[test]
fn compute_aabb_bounds_the_points() {
let aabb = loaded_cloud().compute_aabb();
assert_relative_eq!(aabb.mins, Point3::origin(), epsilon = 1.0e-12);
assert_relative_eq!(aabb.maxs, Point3::new(1.0, 1.0, 1.0), epsilon = 1.0e-12);
}
#[test]
fn debug_summarizes_instead_of_dumping_the_buffer() {
let text = format!("{:?}", loaded_cloud());
assert!(text.contains("points: 4"), "{text}");
}
#[test]
fn transform_moves_points_and_rotates_directions() {
let mut cloud = loaded_cloud();
let iso = Iso3::new(Vector3::new(10.0, 0.0, 0.0), Vector3::z() * FRAC_PI_2);
cloud.transform_in_place(&iso);
assert_relative_eq!(
cloud.points()[1],
Point3::new(10.0, 1.0, 0.0),
epsilon = 1.0e-12
);
assert_relative_eq!(
cloud.point_normals().unwrap()[0].into_inner(),
Vector3::z(),
epsilon = 1.0e-12
);
assert_relative_eq!(
cloud
.point_attr("principal_dir")
.unwrap()
.as_vector()
.unwrap()[0],
Vector3::y(),
epsilon = 1.0e-12
);
assert_eq!(cloud.point_stdev().unwrap(), &[0.1, 0.2, 0.3, 0.4]);
}
#[test]
fn transform_copy_leaves_the_original_alone() {
let cloud = loaded_cloud();
let moved = cloud.transform_copy(&Iso3::translation(5.0, 0.0, 0.0));
assert_relative_eq!(cloud.points()[0], Point3::origin(), epsilon = 1.0e-12);
assert_relative_eq!(
moved.points()[0],
Point3::new(5.0, 0.0, 0.0),
epsilon = 1.0e-12
);
}
#[test]
fn scale_scales_points_and_standard_deviations() -> Result<()> {
let cloud = loaded_cloud().scale_copy(25.4)?;
assert_relative_eq!(
cloud.points()[1],
Point3::new(25.4, 0.0, 0.0),
epsilon = 1.0e-12
);
for (actual, expected) in cloud
.point_stdev()
.unwrap()
.iter()
.zip([0.1, 0.2, 0.3, 0.4].iter())
{
assert_relative_eq!(*actual, expected * 25.4, epsilon = 1.0e-12);
}
Ok(())
}
#[test]
fn a_negative_scale_mirrors_and_flips_the_normals() -> Result<()> {
let mirrored = loaded_cloud().scale_copy(-1.0)?;
assert_relative_eq!(
mirrored.points()[1],
Point3::new(-1.0, 0.0, 0.0),
epsilon = 1.0e-12
);
assert_relative_eq!(
mirrored.point_normals().unwrap()[0].into_inner(),
-Vector3::z(),
epsilon = 1.0e-12
);
for s in mirrored.point_stdev().unwrap() {
assert!(*s > 0.0, "a standard deviation must not go negative");
}
Ok(())
}
#[test]
fn scale_rejects_zero_and_non_finite_factors() {
let mut cloud = loaded_cloud();
assert!(cloud.scale_in_place(0.0).is_err());
assert!(cloud.scale_in_place(f64::NAN).is_err());
assert!(cloud.scale_in_place(f64::INFINITY).is_err());
assert_relative_eq!(
cloud.points()[1],
Point3::new(1.0, 0.0, 0.0),
epsilon = 1.0e-12
);
}
#[test]
fn append_unions_the_attributes() -> Result<()> {
let mut cloud = loaded_cloud();
cloud.append_in_place(&loaded_cloud())?;
assert_eq!(cloud.point_count(), 8);
assert_eq!(
cloud.point_stdev().unwrap(),
&[0.1, 0.2, 0.3, 0.4, 0.1, 0.2, 0.3, 0.4]
);
assert_eq!(cloud.point_attr("confidence").unwrap().len(), 8);
cloud.attrs().validate(cloud.point_count())?;
Ok(())
}
#[test]
fn append_rejects_mismatched_attributes_without_modifying_the_target() -> Result<()> {
let mut cloud = loaded_cloud();
let mut other = loaded_cloud();
other.set_point_stdev(None)?;
assert!(cloud.append_in_place(&other).is_err());
assert_eq!(cloud.point_count(), 4);
assert_eq!(cloud.point_stdev().unwrap(), &[0.1, 0.2, 0.3, 0.4]);
Ok(())
}
#[test]
fn subset_by_mask_carries_every_attribute() -> Result<()> {
let cloud = loaded_cloud();
let mask = IndexMask::try_from_indices(&[1, 3], 4)?;
let sub = cloud.extract_subset_points(&mask)?;
assert_eq!(sub.point_count(), 2);
assert_relative_eq!(sub.points()[0], Point3::new(1.0, 0.0, 0.0), epsilon = 0.0);
assert_eq!(sub.point_stdev().unwrap(), &[0.2, 0.4]);
assert_eq!(sub.point_colors().unwrap(), &[[1, 1, 1], [3, 3, 3]]);
assert_eq!(
sub.point_attr("confidence").unwrap().as_scalar().unwrap(),
&[0.6, 0.8]
);
sub.attrs().validate(sub.point_count())?;
Ok(())
}
#[test]
fn subset_by_mask_rejects_a_length_mismatch() {
let cloud = loaded_cloud();
assert!(
cloud
.extract_subset_points(&IndexMask::new(3, true))
.is_err()
);
}
#[test]
fn subset_by_indices_preserves_order_and_allows_repeats() -> Result<()> {
let cloud = loaded_cloud();
let sub = cloud.extract_subset_indices(&[3, 0, 3])?;
assert_eq!(sub.point_count(), 3);
assert_relative_eq!(sub.points()[0], Point3::new(0.0, 0.0, 1.0), epsilon = 0.0);
assert_relative_eq!(sub.points()[1], Point3::origin(), epsilon = 0.0);
assert_eq!(sub.point_stdev().unwrap(), &[0.4, 0.1, 0.4]);
sub.attrs().validate(sub.point_count())?;
Ok(())
}
#[test]
fn subset_by_indices_rejects_out_of_bounds() {
assert!(loaded_cloud().extract_subset_indices(&[0, 4]).is_err());
}
#[test]
fn reduce_by_voxel_averages_positions() -> Result<()> {
let cloud = PointCloud3::new(vec![
Point3::new(0.0, 0.0, 0.0),
Point3::new(0.2, 0.0, 0.0),
Point3::new(0.0, 0.4, 0.0),
Point3::new(0.2, 0.4, 0.0),
Point3::new(5.5, 0.0, 0.0),
]);
let out = cloud.reduce_by_voxel(1.0)?;
assert_eq!(out.point_count(), 2);
assert_relative_eq!(out.points()[0], Point3::new(0.1, 0.2, 0.0), epsilon = 1e-12);
assert_relative_eq!(out.points()[1], Point3::new(5.5, 0.0, 0.0), epsilon = 1e-12);
let counts = out
.point_attr(VOXEL_COUNT_ATTR)
.and_then(|a| a.as_label())
.expect("counts were written");
assert_eq!(counts, &[4, 1]);
Ok(())
}
#[test]
fn reduce_by_voxel_reports_normal_coherence() -> Result<()> {
let mut cloud = PointCloud3::new(vec![
Point3::new(0.1, 0.0, 0.0),
Point3::new(0.2, 0.0, 0.0),
Point3::new(5.1, 0.0, 0.0),
Point3::new(5.2, 0.0, 0.0),
Point3::new(9.1, 0.0, 0.0),
Point3::new(9.2, 0.0, 0.0),
]);
cloud.set_point_normals(Some(vec![
UnitVec3::new_normalize(Vector3::z()),
UnitVec3::new_normalize(Vector3::z()),
UnitVec3::new_normalize(Vector3::z()),
UnitVec3::new_normalize(Vector3::x()),
UnitVec3::new_normalize(Vector3::z()),
UnitVec3::new_normalize(-Vector3::z()),
]))?;
let out = cloud.reduce_by_voxel(1.0)?;
assert_eq!(out.point_count(), 3);
let coherence = out
.point_attr(VOXEL_COHERENCE_ATTR)
.and_then(|a| a.as_scalar())
.expect("coherence was written");
assert_relative_eq!(coherence[0], 1.0, epsilon = 1e-12);
assert_relative_eq!(coherence[1], 0.5_f64.sqrt(), epsilon = 1e-12);
assert_relative_eq!(coherence[2], 0.0, epsilon = 1e-12);
let normals = out.point_normals().expect("normals were written");
for n in normals {
assert_relative_eq!(n.norm(), 1.0, epsilon = 1e-12);
}
Ok(())
}
#[test]
fn reduce_by_voxel_propagates_stdev() -> Result<()> {
let mut cloud = PointCloud3::new(vec![
Point3::new(0.1, 0.0, 0.0),
Point3::new(0.2, 0.0, 0.0),
Point3::new(0.3, 0.0, 0.0),
Point3::new(0.4, 0.0, 0.0),
]);
cloud.set_point_stdev(Some(vec![0.01; 4]))?;
let out = cloud.reduce_by_voxel(1.0)?;
let stdev = out.point_stdev().expect("stdev was written");
assert_eq!(stdev.len(), 1);
assert_relative_eq!(stdev[0], 0.01 / 2.0, epsilon = 1e-12);
Ok(())
}
#[test]
fn reduce_by_voxel_takes_the_modal_label() -> Result<()> {
let mut cloud = PointCloud3::new(vec![
Point3::new(0.1, 0.0, 0.0),
Point3::new(0.2, 0.0, 0.0),
Point3::new(0.3, 0.0, 0.0),
Point3::new(5.1, 0.0, 0.0),
Point3::new(5.2, 0.0, 0.0),
]);
cloud.insert_point_attr("pass", Attr3::Label(vec![7, 7, 3, 9, 4]))?;
let out = cloud.reduce_by_voxel(1.0)?;
let labels = out
.point_attr("pass")
.and_then(|a| a.as_label())
.expect("the label attribute came through");
assert_eq!(labels, &[7, 4]);
Ok(())
}
#[test]
fn reduce_by_voxel_averages_open_map_scalars_and_colors() -> Result<()> {
let mut cloud =
PointCloud3::new(vec![Point3::new(0.1, 0.0, 0.0), Point3::new(0.2, 0.0, 0.0)]);
cloud.insert_point_attr("deviation", Attr3::Scalar(vec![1.0, 3.0]))?;
cloud.set_point_colors(Some(vec![[0, 10, 255], [2, 11, 255]]))?;
let out = cloud.reduce_by_voxel(1.0)?;
let dev = out
.point_attr("deviation")
.and_then(|a| a.as_scalar())
.expect("scalar came through");
assert_relative_eq!(dev[0], 2.0, epsilon = 1e-12);
assert_eq!(
out.point_colors().expect("colors came through"),
&[[1, 11, 255]]
);
Ok(())
}
#[test]
fn reduce_by_voxel_refuses_to_overwrite_its_own_attributes() -> Result<()> {
let mut cloud = PointCloud3::new(vec![Point3::origin()]);
cloud.insert_point_attr(VOXEL_COUNT_ATTR, Attr3::Label(vec![1]))?;
assert!(cloud.reduce_by_voxel(1.0).is_err());
Ok(())
}
#[test]
fn reduce_by_voxel_rejects_a_nonsense_size() {
let cloud = PointCloud3::new(vec![Point3::origin()]);
assert!(cloud.reduce_by_voxel(0.0).is_err());
assert!(cloud.reduce_by_voxel(f64::NAN).is_err());
}
#[test]
fn a_mesh_reduces_through_a_sample_without_mesh_specific_code() -> Result<()> {
let mesh = crate::Mesh3::create_sphere(50.0, 0.077)?;
let cloud = mesh.sample_dense(1.0, None).unwrap();
assert!(
cloud.point_normals().is_some(),
"the sample carried normals"
);
let out = cloud.reduce_by_voxel(5.0)?;
assert!(out.point_count() < cloud.point_count() / 4);
assert!(out.point_normals().is_some());
let coherence = out
.point_attr(VOXEL_COHERENCE_ATTR)
.and_then(|a| a.as_scalar())
.expect("coherence was written");
let worst = coherence.iter().copied().fold(f64::INFINITY, f64::min);
assert!(
worst > 0.9,
"worst coherence on a smooth sphere was {worst}"
);
Ok(())
}
#[test]
fn reduce_by_voxel_coherence_finds_the_edges_of_a_box() -> Result<()> {
let mesh = crate::Mesh3::create_box(40.0, 40.0, 40.0, false);
let cloud = mesh.sample_dense(0.5, None).unwrap();
let out = cloud.reduce_by_voxel(4.0)?;
let coherence = out
.point_attr(VOXEL_COHERENCE_ATTR)
.and_then(|a| a.as_scalar())
.expect("coherence was written");
let worst = coherence.iter().copied().fold(f64::INFINITY, f64::min);
let best = coherence.iter().copied().fold(f64::NEG_INFINITY, f64::max);
assert!(
best > 0.99,
"a flat face should be almost perfectly coherent"
);
assert!(
worst < 0.9,
"an edge voxel should be measurably less coherent, worst was {worst}"
);
Ok(())
}
#[test]
fn reduce_by_voxel_keeps_a_sphere_on_its_surface() -> Result<()> {
let radius = 50.0;
let n = 20_000;
let golden = std::f64::consts::PI * (3.0 - 5.0_f64.sqrt());
let points: Vec<Point3> = (0..n)
.map(|i| {
let y = 1.0 - (i as f64 / (n as f64 - 1.0)) * 2.0;
let r = (1.0 - y * y).max(0.0).sqrt();
let theta = golden * i as f64;
Point3::new(
radius * theta.cos() * r,
radius * y,
radius * theta.sin() * r,
)
})
.collect();
let voxel = 5.0;
let out = PointCloud3::new(points).reduce_by_voxel(voxel)?;
assert!(out.point_count() < n / 4, "the reduction did not reduce");
let limit = voxel * 3.0_f64.sqrt() / 2.0;
for p in out.points() {
assert!(
(p.coords.norm() - radius).abs() < limit,
"reduced point {p:?} left the sphere by more than {limit}"
);
}
Ok(())
}
#[test]
fn indexing_a_cloud_does_not_disturb_its_attributes() -> Result<()> {
let cloud = loaded_cloud();
let index = cloud.compute_index()?;
assert_eq!(index.points(), cloud.points());
assert_eq!(index.len(), cloud.point_count());
for (i, p) in cloud.points().iter().enumerate() {
let (found, d) = index.nearest_one(p);
assert_eq!(found, i);
assert!(d < 1e-12);
}
assert!(cloud.point_attr("confidence").is_some());
Ok(())
}
#[test]
fn check_attribute_loss_only_complains_when_there_is_something_to_lose() -> Result<()> {
let bare = PointCloud3::new(vec![Point3::origin()]);
bare.check_attribute_loss("XYZ", false)?;
let loaded = loaded_cloud();
assert!(loaded.check_attribute_loss("XYZ", false).is_err());
loaded.check_attribute_loss("XYZ", true)?;
Ok(())
}
#[cfg(feature = "ply")]
struct TempPly {
path: std::path::PathBuf,
}
#[cfg(feature = "ply")]
impl TempPly {
fn new(name: &str) -> Self {
let path = std::env::temp_dir().join(format!(
"engeom-cloud-{}-{}.ply",
name,
std::process::id()
));
Self { path }
}
fn path(&self) -> &Path {
&self.path
}
}
#[cfg(feature = "ply")]
impl Drop for TempPly {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.path);
}
}
#[cfg(feature = "ply")]
#[test]
fn a_ply_round_trip_preserves_every_attribute() -> Result<()> {
let before = loaded_cloud();
let file = TempPly::new("round-trip");
before.save_ply(file.path(), &PlyWriteOpts::default())?;
let after = PointCloud3::load_ply(file.path())?;
assert_eq!(after.point_count(), before.point_count());
for (p, q) in before.points().iter().zip(after.points()) {
assert_relative_eq!(p, q, epsilon = 0.0);
}
assert_eq!(after.point_colors(), before.point_colors());
assert_eq!(after.point_stdev(), before.point_stdev());
assert_eq!(
after.point_attr("confidence"),
before.point_attr("confidence")
);
assert_eq!(
after.point_attr("principal_dir"),
before.point_attr("principal_dir")
);
for (a, b) in after
.point_normals()
.unwrap()
.iter()
.zip(before.point_normals().unwrap())
{
assert_relative_eq!(a.into_inner(), b.into_inner(), epsilon = 1.0e-15);
}
Ok(())
}
#[cfg(feature = "ply")]
#[test]
fn load_ply_refuses_a_file_which_is_really_a_mesh() -> Result<()> {
use crate::geom3::MeshData3;
let mesh = MeshData3::new(
vec![
Point3::new(0.0, 0.0, 0.0),
Point3::new(1.0, 0.0, 0.0),
Point3::new(0.0, 1.0, 0.0),
],
vec![[0, 1, 2]],
)?;
let file = TempPly::new("is-a-mesh");
mesh.save_ply(file.path(), &PlyWriteOpts::default())?;
let result = PointCloud3::load_ply(file.path());
assert!(result.is_err());
let message = result.unwrap_err().to_string();
assert!(message.contains("MeshData3::load_ply"), "{message}");
Ok(())
}
#[cfg(feature = "ply")]
#[test]
fn a_bare_cloud_round_trips_without_inventing_attributes() -> Result<()> {
let before = PointCloud3::new(vec![
Point3::new(1.0, 2.0, 3.0),
Point3::new(-4.0, 5.0, -6.0),
]);
let file = TempPly::new("bare");
before.save_ply(file.path(), &PlyWriteOpts::default())?;
let after = PointCloud3::load_ply(file.path())?;
assert_eq!(after.point_count(), 2);
assert!(after.attrs().is_empty());
Ok(())
}
}