use std::rc::Rc;
use crate::core::{BufferGeometry, Intersection, Object3D, ObjectRef, Raycaster};
use crate::materials::MeshBasicNodeMaterial;
use crate::math::{Matrix4, Sphere, Vector3};
use crate::objects::Payload;
#[derive(Clone)]
pub struct Points {
pub geometry: Rc<BufferGeometry>,
pub material: Option<MeshBasicNodeMaterial>,
pub count: Option<usize>,
}
impl Points {
#[allow(clippy::new_ret_no_self)] pub fn new(geometry: Rc<BufferGeometry>, material: MeshBasicNodeMaterial) -> ObjectRef {
let mut object = Object3D {
object_type: "Points",
..Default::default()
};
object.payload = Payload::Points(Self {
geometry,
material: Some(material),
count: None,
});
object.into_node()
}
pub(crate) fn bounding_sphere_in(&self, matrix_world: &Matrix4) -> Option<Sphere> {
let bounding_sphere = self.geometry.compute_bounding_sphere()?;
let mut sphere = Sphere::new(bounding_sphere.center, bounding_sphere.radius);
sphere.apply_matrix4(matrix_world);
Some(sphere)
}
pub fn raycast(
&self,
matrix_world: &Matrix4,
scale: &Vector3,
object: &ObjectRef,
raycaster: &Raycaster,
intersects: &mut Vec<Intersection>,
) {
let geometry = &self.geometry;
let threshold = raycaster.params.points.threshold;
let draw_range = geometry.draw_range;
let Some(mut sphere) = self.bounding_sphere_in(matrix_world) else {
return;
};
sphere.radius += threshold;
if !raycaster.ray.intersects_sphere(&sphere) {
return;
}
let mut inverse_matrix = *matrix_world;
inverse_matrix.invert();
let mut ray = raycaster.ray;
ray.apply_matrix4(&inverse_matrix);
let local_threshold = threshold / ((scale.x + scale.y + scale.z) / 3.0);
let local_threshold_sq = local_threshold * local_threshold;
let Some(position) = geometry.position() else {
return;
};
let end_of = |count: usize| match draw_range.count {
Some(draw_count) => count.min(draw_range.start + draw_count),
None => count,
};
let mut test_point = |index: usize| {
let point = position.get_vector3(index);
let ray_point_distance_sq = ray.distance_sq_to_point(&point);
if ray_point_distance_sq < local_threshold_sq {
let mut intersect_point = ray.closest_point_to_point(&point);
intersect_point.apply_matrix4(matrix_world);
let distance = raycaster.ray.origin.distance_to(&intersect_point);
if distance < raycaster.near || distance > raycaster.far {
return;
}
let mut intersection = Intersection::new(distance, intersect_point, object.clone());
intersection.distance_to_ray = Some(ray_point_distance_sq.sqrt());
intersection.index = Some(index);
intersects.push(intersection);
}
};
if let Some(index) = &geometry.index {
for i in draw_range.start..end_of(index.count()) {
test_point(index.get_x(i));
}
} else {
for i in draw_range.start..end_of(position.count()) {
test_point(i);
}
}
}
}