use crate::common::IndexMask;
use crate::geom3::Aabb3;
use crate::geom3::attributes3::{Attr3, PointAttrSet3};
use crate::{Iso3, Point3, PointCloud, PointCloudFeatures, Result, UnitVec3};
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 PointCloudData3 {
points: Vec<Point3>,
attrs: PointAttrSet3,
}
impl PointCloudData3 {
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_cloud(cloud: &PointCloud) -> Result<Self> {
let n = cloud.points().len();
let mut attrs = PointAttrSet3::empty();
attrs.set_normals(cloud.normals().map(|v| v.to_vec()), n)?;
attrs.set_colors(cloud.colors().map(|v| v.to_vec()), n)?;
attrs.set_stdev(cloud.std_devs().map(|v| v.to_vec()), n)?;
Ok(Self {
points: cloud.points().to_vec(),
attrs,
})
}
pub fn to_cloud(&self) -> Result<PointCloud> {
PointCloud::try_new(
self.points.clone(),
self.attrs.normals().map(|v| v.to_vec()),
self.attrs.colors().map(|v| v.to_vec()),
self.attrs.stdev().map(|v| v.to_vec()),
)
}
pub fn into_parts(self) -> (Vec<Point3>, PointAttrSet3) {
(self.points, self.attrs)
}
}
impl PointCloudData3 {
#[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 PointCloudData3 {
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 PointCloudData3 {
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_attr(&self, name: &str) -> Option<&Attr3> {
self.attrs.attr(name)
}
}
impl PointCloudData3 {
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 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 PointCloudData3 {
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: &PointCloudData3) -> Result<()> {
self.attrs.extend_from(&other.attrs)?;
self.points.extend_from_slice(&other.points);
Ok(())
}
}
impl PointCloudData3 {
pub fn create_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 create_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)?,
})
}
}
impl fmt::Debug for PointCloudData3 {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("PointCloudData3")
.field("points", &self.points.len())
.field("attrs", &self.attrs)
.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Vector3;
use approx::assert_relative_eq;
use std::f64::consts::FRAC_PI_2;
fn loaded_cloud() -> PointCloudData3 {
let mut cloud = PointCloudData3::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 = PointCloudData3::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 = PointCloudData3::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!(PointCloudData3::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.create_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
.create_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.create_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().create_subset_indices(&[0, 4]).is_err());
}
#[test]
fn round_trip_through_point_cloud_keeps_the_typed_attributes() -> Result<()> {
let before = loaded_cloud();
let cloud = before.to_cloud()?;
let after = PointCloudData3::from_cloud(&cloud)?;
assert_eq!(after.points(), before.points());
assert_eq!(after.point_colors(), before.point_colors());
assert_eq!(after.point_stdev(), before.point_stdev());
assert_eq!(after.point_normals(), before.point_normals());
assert!(after.point_attr("confidence").is_none());
Ok(())
}
#[test]
fn check_attribute_loss_only_complains_when_there_is_something_to_lose() -> Result<()> {
let bare = PointCloudData3::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 = PointCloudData3::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 = PointCloudData3::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 = PointCloudData3::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 = PointCloudData3::load_ply(file.path())?;
assert_eq!(after.point_count(), 2);
assert!(after.attrs().is_empty());
Ok(())
}
}