Skip to main content

three_rs/objects/
points.rs

1//! Port of `three.js/src/objects/Points.js`.
2//!
3//! `Points extends Object3D` — like `Line`, it is *not* a `Mesh`, and the
4//! renderer keeps them apart because
5//! `WebGPUUtils.getPrimitiveTopology( object, material )` reads the object:
6//! `object.isPoints` is the first arm, and it is what turns the pipeline's
7//! topology into `point-list`. A WebGPU point primitive is always one pixel,
8//! which is why `webgpu_compute_points` draws 300 000 of them rather than
9//! 300 000 sprites.
10
11use std::rc::Rc;
12
13use crate::core::{BufferGeometry, Intersection, Object3D, ObjectRef, Raycaster};
14use crate::materials::MeshBasicNodeMaterial;
15use crate::math::{Matrix4, Sphere, Vector3};
16use crate::objects::Payload;
17
18/// The state `Points` adds to `Object3D`: `geometry` and `material`, plus the
19/// non-standard `count` the compute examples set.
20#[derive(Clone)]
21pub struct Points {
22    /// `Points.geometry`.
23    pub geometry: Rc<BufferGeometry>,
24    /// `Points.material`.
25    pub material: Option<MeshBasicNodeMaterial>,
26    /// `mesh.count`, which is **not** a `Points` property in three.js. The
27    /// renderer picks it up anyway: `RenderObject.getInstanceCount()`
28    /// (`src/renderers/common/RenderObject.js:623-627`) is
29    /// `instanced geometry ? … : object.count !== undefined ? max( 0, object.count ) : 1`,
30    /// so `webgpu_compute_points`' `mesh.count = 300000` on a one-vertex
31    /// geometry becomes `draw( 1, 300000, 0, 0 )`. Reproduced deliberately —
32    /// see `docs/rung12-progress.md`.
33    pub count: Option<usize>,
34}
35
36impl Points {
37    /// `new Points( geometry, material )`.
38    #[allow(clippy::new_ret_no_self)] // `new` mirrors three.js's constructor and returns a scene-graph `ObjectRef`, not `Self`; public API, not changing.
39    pub fn new(geometry: Rc<BufferGeometry>, material: MeshBasicNodeMaterial) -> ObjectRef {
40        let mut object = Object3D {
41            object_type: "Points",
42            ..Default::default()
43        };
44        object.payload = Payload::Points(Self {
45            geometry,
46            material: Some(material),
47            count: None,
48        });
49        object.into_node()
50    }
51
52    /// The geometry half of `frustum.intersectsObject( points )` — identical to
53    /// `Mesh`', because `Frustum.intersectsObject()` only reads
54    /// `geometry.boundingSphere`.
55    pub(crate) fn bounding_sphere_in(&self, matrix_world: &Matrix4) -> Option<Sphere> {
56        let bounding_sphere = self.geometry.compute_bounding_sphere()?;
57        let mut sphere = Sphere::new(bounding_sphere.center, bounding_sphere.radius);
58        sphere.apply_matrix4(matrix_world);
59        Some(sphere)
60    }
61
62    /// `Points.raycast( raycaster, intersects )` — every point within
63    /// `raycaster.params.points.threshold` of the ray. `scale` is the node's
64    /// local `scale`, which three.js divides the threshold by.
65    pub fn raycast(
66        &self,
67        matrix_world: &Matrix4,
68        scale: &Vector3,
69        object: &ObjectRef,
70        raycaster: &Raycaster,
71        intersects: &mut Vec<Intersection>,
72    ) {
73        let geometry = &self.geometry;
74        let threshold = raycaster.params.points.threshold;
75        let draw_range = geometry.draw_range;
76
77        // Check the bounding sphere's distance to the ray.
78        let Some(mut sphere) = self.bounding_sphere_in(matrix_world) else {
79            return;
80        };
81        sphere.radius += threshold;
82        if !raycaster.ray.intersects_sphere(&sphere) {
83            return;
84        }
85
86        let mut inverse_matrix = *matrix_world;
87        inverse_matrix.invert();
88        let mut ray = raycaster.ray;
89        ray.apply_matrix4(&inverse_matrix);
90
91        let local_threshold = threshold / ((scale.x + scale.y + scale.z) / 3.0);
92        let local_threshold_sq = local_threshold * local_threshold;
93
94        let Some(position) = geometry.position() else {
95            return;
96        };
97        let end_of = |count: usize| match draw_range.count {
98            Some(draw_count) => count.min(draw_range.start + draw_count),
99            None => count,
100        };
101
102        // `testPoint( point, index, localThresholdSq, matrixWorld, raycaster,
103        // intersects, object )`.
104        let mut test_point = |index: usize| {
105            let point = position.get_vector3(index);
106            let ray_point_distance_sq = ray.distance_sq_to_point(&point);
107            if ray_point_distance_sq < local_threshold_sq {
108                let mut intersect_point = ray.closest_point_to_point(&point);
109                intersect_point.apply_matrix4(matrix_world);
110                let distance = raycaster.ray.origin.distance_to(&intersect_point);
111                if distance < raycaster.near || distance > raycaster.far {
112                    return;
113                }
114                let mut intersection = Intersection::new(distance, intersect_point, object.clone());
115                intersection.distance_to_ray = Some(ray_point_distance_sq.sqrt());
116                intersection.index = Some(index);
117                intersects.push(intersection);
118            }
119        };
120
121        if let Some(index) = &geometry.index {
122            for i in draw_range.start..end_of(index.count()) {
123                test_point(index.get_x(i));
124            }
125        } else {
126            for i in draw_range.start..end_of(position.count()) {
127                test_point(i);
128            }
129        }
130    }
131}