Skip to main content

three_rs/objects/
line.rs

1//! Ports of `three.js/src/objects/Line.js` and `three.js/src/objects/LineSegments.js`.
2//!
3//! `Line extends Object3D` — it is *not* a `Mesh`, and the renderer keeps them
4//! apart: `WebGPUUtils.getPrimitiveTopology()` reads the object, not the
5//! material, so the same `LineBasicNodeMaterial` draws a `line-strip` under a
6//! `Line` and a `line-list` under a `LineSegments`.
7//!
8//! `LineLoop` is deliberately absent. `Renderer._projectObject()` errors on it
9//! ("Objects of type THREE.LineLoop are not supported. Please use THREE.Line or
10//! THREE.LineSegments."), so there is nothing to port.
11//!
12//! `computeLineDistances()` is not ported either: its only consumer is
13//! `LineDashedMaterial` / `dashSize`, which no rung needs.
14
15use std::rc::Rc;
16
17use crate::core::{BufferGeometry, Intersection, Object3D, ObjectRef, Raycaster, TypedArray};
18use crate::materials::MeshBasicNodeMaterial;
19use crate::math::{Matrix4, Ray, Sphere, Vector3};
20use crate::objects::Payload;
21
22/// The state `Line` adds to `Object3D`: `geometry` and `material`, exactly as
23/// `Mesh` has them. It lives in a node's [`Payload`](crate::objects::Payload) —
24/// see `docs/scene-graph.md`.
25#[derive(Clone)]
26pub struct Line {
27    /// `Line.geometry`.
28    pub geometry: Rc<BufferGeometry>,
29    /// `Line.material`.
30    pub material: Option<MeshBasicNodeMaterial>,
31    /// `LineSegments.isLineSegments`. The single bit that separates the two
32    /// subclasses for everything this port does with them.
33    pub is_line_segments: bool,
34}
35
36impl Line {
37    /// `new Line( geometry, material )`.
38    ///
39    /// three.js defaults the material to `new LineBasicMaterial()`, which under
40    /// `WebGPURenderer` is a `LineBasicNodeMaterial`; the port takes it by value
41    /// because every call site on the ladder passes one.
42    #[allow(clippy::new_ret_no_self)] // `new` mirrors three.js's constructor and returns a scene-graph `ObjectRef`, not `Self`; public API, not changing.
43    pub fn new(geometry: Rc<BufferGeometry>, material: MeshBasicNodeMaterial) -> ObjectRef {
44        Self::node(geometry, material, false)
45    }
46
47    /// The geometry half of `Line.intersectsFrustum( frustum )`, i.e.
48    /// `frustum.intersectsObject( line )`: the bounding sphere pushed through
49    /// `matrixWorld`. Identical to `Mesh`', because `Frustum.intersectsObject()`
50    /// only ever reads `geometry.boundingSphere`.
51    pub(crate) fn bounding_sphere_in(&self, matrix_world: &Matrix4) -> Option<Sphere> {
52        let bounding_sphere = self.geometry.compute_bounding_sphere()?;
53        let mut sphere = Sphere::new(bounding_sphere.center, bounding_sphere.radius);
54        sphere.apply_matrix4(matrix_world);
55        Some(sphere)
56    }
57
58    /// `Line.raycast( raycaster, intersects )` — every segment that passes
59    /// within `raycaster.params.line.threshold` of the ray. `scale` is the
60    /// node's local `scale`, which three.js divides the threshold by.
61    ///
62    /// `LineSegments` walks the vertices two at a time, `Line` one at a time.
63    pub fn raycast(
64        &self,
65        matrix_world: &Matrix4,
66        scale: &Vector3,
67        object: &ObjectRef,
68        raycaster: &Raycaster,
69        intersects: &mut Vec<Intersection>,
70    ) {
71        let geometry = &self.geometry;
72        let threshold = raycaster.params.line.threshold;
73        let draw_range = geometry.draw_range;
74
75        // Check the bounding sphere's distance to the ray.
76        let Some(mut sphere) = self.bounding_sphere_in(matrix_world) else {
77            return;
78        };
79        sphere.radius += threshold;
80        if !raycaster.ray.intersects_sphere(&sphere) {
81            return;
82        }
83
84        let mut inverse_matrix = *matrix_world;
85        inverse_matrix.invert();
86        let mut ray = raycaster.ray;
87        ray.apply_matrix4(&inverse_matrix);
88
89        let local_threshold = threshold / ((scale.x + scale.y + scale.z) / 3.0);
90        let local_threshold_sq = local_threshold * local_threshold;
91
92        let step = if self.is_line_segments { 2 } else { 1 };
93        let Some(position) = geometry.position() else {
94            return;
95        };
96        let end_of = |count: usize| match draw_range.count {
97            Some(draw_count) => count.min(draw_range.start + draw_count),
98            None => count,
99        };
100
101        let mut check = |a: usize, b: usize, i: usize| {
102            let start = position.get_vector3(a);
103            let end = position.get_vector3(b);
104            if let Some(intersect) = check_intersection(
105                matrix_world,
106                object,
107                raycaster,
108                &ray,
109                local_threshold_sq,
110                &start,
111                &end,
112                i,
113            ) {
114                intersects.push(intersect);
115            }
116        };
117
118        let start = draw_range.start;
119        if let Some(index) = &geometry.index {
120            let end = end_of(index.count());
121            let mut i = start;
122            while i + 1 < end {
123                check(index.get_x(i), index.get_x(i + 1), i);
124                i += step;
125            }
126        } else {
127            let end = end_of(position.count());
128            let mut i = start;
129            while i + 1 < end {
130                check(i, i + 1, i);
131                i += step;
132            }
133        }
134    }
135
136    /// Rewrite the line's `position` attribute and mark it for re-upload —
137    /// `positions` is the flat `[ x, y, z, x, y, z, ... ]` of values, `item_size`
138    /// per vertex.
139    ///
140    /// The convenience form of `setXYZ()` per vertex then
141    /// [`set_needs_update`](crate::core::BufferAttribute::set_needs_update),
142    /// which is what a consumer moving one wall of a diagram wants instead of
143    /// rebuilding the scene (issue #47). The next render re-writes that one
144    /// buffer; the geometry keeps its id and its other buffers.
145    ///
146    /// Any array kind takes the values as `setXYZ()` would (normalized and
147    /// narrowed); an own `Float32Array` is copied straight in. An attribute
148    /// with its own array takes a new length (its array is rebuilt in the same
149    /// kind); an interleaved one keeps its count.
150    ///
151    /// # Panics
152    ///
153    /// If the geometry has no `position` attribute, or it is interleaved and
154    /// `positions` is longer than its items.
155    pub fn set_positions(&self, positions: &[f32]) {
156        let attribute = self
157            .geometry
158            .get_attribute("position")
159            .expect("three-rs: the line geometry has a position attribute");
160
161        let interleaved = attribute.is_interleaved();
162        let mut data = attribute.data_mut();
163        match data.as_f32_mut() {
164            Some(array) if !interleaved => {
165                array.clear();
166                array.extend_from_slice(positions);
167            }
168            _ => {
169                if !interleaved && data.len() != positions.len() {
170                    *data = TypedArray::zeros(data.kind(), positions.len());
171                }
172                drop(data);
173                let item_size = attribute.item_size;
174                for (i, item) in positions.chunks(item_size).enumerate() {
175                    for (c, value) in item.iter().enumerate() {
176                        attribute.store(i, c, f64::from(*value));
177                    }
178                }
179            }
180        }
181
182        attribute.set_needs_update();
183    }
184
185    fn node(
186        geometry: Rc<BufferGeometry>,
187        material: MeshBasicNodeMaterial,
188        is_line_segments: bool,
189    ) -> ObjectRef {
190        let mut object = Object3D {
191            object_type: if is_line_segments {
192                "LineSegments"
193            } else {
194                "Line"
195            },
196            ..Default::default()
197        };
198        object.payload = Payload::Line(Self {
199            geometry,
200            material: Some(material),
201            is_line_segments,
202        });
203        object.into_node()
204    }
205}
206
207/// `class LineSegments extends Line` — a series of lines drawn between *pairs*
208/// of vertices, i.e. `line-list` rather than `line-strip`. The only state it
209/// adds is `isLineSegments`, so it is a constructor on [`Line`]'s payload
210/// rather than a payload of its own.
211pub struct LineSegments;
212
213impl LineSegments {
214    /// `new LineSegments( geometry, material )`.
215    #[allow(clippy::new_ret_no_self)] // `new` mirrors three.js's constructor and returns a scene-graph `ObjectRef`, not `Self`; public API, not changing.
216    pub fn new(geometry: Rc<BufferGeometry>, material: MeshBasicNodeMaterial) -> ObjectRef {
217        Line::node(geometry, material, true)
218    }
219}
220
221/// `Line.js`' `checkIntersection( object, raycaster, ray, thresholdSq, a, b, i )`,
222/// with the two endpoints already read.
223#[allow(clippy::too_many_arguments)]
224fn check_intersection(
225    matrix_world: &Matrix4,
226    object: &ObjectRef,
227    raycaster: &Raycaster,
228    ray: &Ray,
229    threshold_sq: f64,
230    start: &Vector3,
231    end: &Vector3,
232    i: usize,
233) -> Option<Intersection> {
234    let mut point_on_ray = Vector3::ZERO;
235    let mut point_on_segment = Vector3::ZERO;
236    let dist_sq = ray.distance_sq_to_segment(
237        start,
238        end,
239        Some(&mut point_on_ray),
240        Some(&mut point_on_segment),
241    );
242    if dist_sq > threshold_sq {
243        return None;
244    }
245
246    // Move back to world space for the distance calculation.
247    point_on_ray.apply_matrix4(matrix_world);
248    let distance = raycaster.ray.origin.distance_to(&point_on_ray);
249    if distance < raycaster.near || distance > raycaster.far {
250        return None;
251    }
252
253    // three.js reports the point on the *segment*, not on the ray.
254    point_on_segment.apply_matrix4(matrix_world);
255    let mut intersection = Intersection::new(distance, point_on_segment, object.clone());
256    intersection.index = Some(i);
257    Some(intersection)
258}