three_rs/objects/mesh.rs
1//! Port of `three.js/src/objects/Mesh.js` (rung 1 subset).
2
3use std::rc::Rc;
4
5use crate::core::{BufferGeometry, Face, Intersection, Object3D, ObjectRef, Raycaster};
6use crate::materials::{MeshBasicNodeMaterial, Side};
7use crate::math::{Box3, Matrix4, Ray, Sphere, Triangle, Vector2, Vector3};
8use crate::objects::Payload;
9
10/// The state `Mesh` adds to `Object3D`. It lives in a node's
11/// [`Payload`](crate::objects::Payload) rather than wrapping an `Object3D`,
12/// because the renderer finds meshes by walking the tree — see
13/// `docs/scene-graph.md`.
14#[derive(Clone)]
15pub struct Mesh {
16 /// `Mesh.geometry`.
17 pub geometry: Rc<BufferGeometry>,
18 /// `Mesh.material` when it is a single material.
19 pub material: Option<MeshBasicNodeMaterial>,
20 /// `Mesh.material` when it is an *array* — `Array.isArray( material )`.
21 ///
22 /// three.js has one property that holds either a material or an array of
23 /// them; the port keeps the array form here, beside
24 /// [`material`](Self::material), and a mesh built with
25 /// [`Mesh::with_materials`] has `material: None` and a non-empty
26 /// `materials`. `Renderer._projectObject()` then pushes one render item
27 /// per entry of `geometry.groups`, drawn with `materials[
28 /// group.materialIndex ]` over the group's index (or vertex) range — see
29 /// `docs/nodes.md` §51.
30 pub materials: Vec<MeshBasicNodeMaterial>,
31 /// `Mesh.morphTargetInfluences` — one weight per `morphAttributes.position`
32 /// entry, filled in by `updateMorphTargets()` from the constructor.
33 pub morph_target_influences: Vec<f64>,
34 /// `Some` when this mesh is a
35 /// [`LineSegments2`](crate::addons::lines::LineSegments2): the object's
36 /// own state (its `_resolution`), which also routes `raycast()` to the
37 /// fat-line version. The segments themselves are on the geometry, as
38 /// `instanceStart` / `instanceEnd` interleaved views.
39 pub line_segments: Option<crate::addons::lines::LineSegments2State>,
40 /// `mesh.count`, which is **not** a `Mesh` property in three.js: a page
41 /// sets it ad hoc (`webgpu_instance_path`'s `mesh.count = 1000`,
42 /// `webgpu_particles`' `smokeInstancedSprite.count = 2000`) and
43 /// `RenderObject.getInstanceCount()` (`RenderObject.js:617-631`) reads it
44 /// as `object.count !== undefined ? max( 0, object.count ) : 1`, so a
45 /// plain mesh — one whose geometry is not an `InstancedBufferGeometry` —
46 /// draws that many instances, and a node tells them apart through
47 /// `instanceIndex` or an `instancedBufferAttribute`. `None` is
48 /// `undefined`. [`Points::count`](crate::objects::Points) is the same
49 /// thing on `Points`.
50 pub count: Option<usize>,
51}
52
53impl Mesh {
54 /// `new Mesh( geometry, material )`, as a scene-graph [`ObjectRef`].
55 ///
56 /// The material is `impl Into<Option<MeshBasicNodeMaterial>>`, so a call
57 /// passes the material by value as `Line::new` and `InstancedMesh::new` do,
58 /// or `None` where three.js leaves `material` undefined and the renderer
59 /// falls back to a default white `MeshBasicMaterial` — which is what
60 /// `webgpu_postprocessing_masking` and `webgpu_depth_texture` rely on,
61 /// together with `scene.overrideMaterial`.
62 #[allow(clippy::new_ret_no_self)] // `new` mirrors three.js's constructor and returns a scene-graph `ObjectRef`, not `Self`; public API, not changing.
63 pub fn new(
64 geometry: Rc<BufferGeometry>,
65 material: impl Into<Option<MeshBasicNodeMaterial>>,
66 ) -> ObjectRef {
67 let mut object = Object3D {
68 object_type: "Mesh",
69 ..Default::default()
70 };
71 // `this.updateMorphTargets()`: `morphTargetInfluences` gets one 0 per
72 // morph attribute of the first key in `geometry.morphAttributes`.
73 let morph_target_influences = match geometry.morph_attributes().next() {
74 Some((_, attributes)) => vec![0.0; attributes.len()],
75 None => Vec::new(),
76 };
77
78 object.payload = Payload::Mesh(Self {
79 geometry,
80 material: material.into(),
81 materials: Vec::new(),
82 morph_target_influences,
83 line_segments: None,
84 count: None,
85 });
86 object.into_node()
87 }
88
89 /// `new Mesh( geometry, materials )` with an array of materials: each of
90 /// `geometry.groups` is drawn with `materials[ group.materialIndex ]`.
91 /// A group whose index has no material is skipped, as three.js'
92 /// `if ( groupMaterial && groupMaterial.visible )` skips it.
93 pub fn with_materials(
94 geometry: Rc<BufferGeometry>,
95 materials: Vec<MeshBasicNodeMaterial>,
96 ) -> ObjectRef {
97 let node = Self::new(geometry, None);
98 if let Payload::Mesh(mesh) = &mut node.borrow_mut().payload {
99 mesh.materials = materials;
100 }
101 node
102 }
103
104 /// The `Mesh` state alone, for a caller that already has the [`ObjectRef`] to
105 /// install it on — `GLTFLoader`, whose tree node exists before the
106 /// primitive that turns it into a mesh, the way
107 /// [`SkinnedMesh::of`](crate::objects::SkinnedMesh::of) serves the skinned
108 /// half.
109 pub fn of(geometry: Rc<BufferGeometry>, material: Option<MeshBasicNodeMaterial>) -> Self {
110 let morph_target_influences = match geometry.morph_attributes().next() {
111 Some((_, attributes)) => vec![0.0; attributes.len()],
112 None => Vec::new(),
113 };
114
115 Self {
116 geometry,
117 material,
118 materials: Vec::new(),
119 morph_target_influences,
120 line_segments: None,
121 count: None,
122 }
123 }
124
125 /// `Mesh.intersectsFrustum( frustum )` needs the world matrix, which lives on
126 /// the node; this is the geometry half, i.e. the bounding sphere three.js
127 /// lazily computes in `_projectObject`.
128 pub(crate) fn bounding_sphere_in(&self, matrix_world: &Matrix4) -> Option<crate::math::Sphere> {
129 let bounding_sphere = self.geometry.compute_bounding_sphere()?;
130 let mut sphere = crate::math::Sphere::new(bounding_sphere.center, bounding_sphere.radius);
131 sphere.apply_matrix4(matrix_world);
132 Some(sphere)
133 }
134
135 /// `Mesh.getVertexPosition( index, target )` — the vertex's position with
136 /// the morph targets applied, as the vertex shader would place it before
137 /// skinning.
138 pub fn get_vertex_position(&self, index: usize) -> Vector3 {
139 vertex_position(&self.geometry, &self.morph_target_influences, index)
140 }
141
142 /// `Mesh.raycast( raycaster, intersects )`, for the node `object` whose
143 /// `matrixWorld` is `matrix_world`.
144 ///
145 /// three.js returns early when `material === undefined`; a port mesh with
146 /// no material draws with the renderer's default `MeshBasicMaterial`
147 /// (`FrontSide`), which is what three's constructor would have given it,
148 /// so it raycasts as front-sided instead.
149 pub fn raycast(
150 &self,
151 matrix_world: &Matrix4,
152 object: &ObjectRef,
153 raycaster: &Raycaster,
154 intersects: &mut Vec<Intersection>,
155 ) {
156 let Some(bounding_sphere) = self.geometry.compute_bounding_sphere() else {
157 return;
158 };
159 let sphere = Sphere::new(bounding_sphere.center, bounding_sphere.radius);
160 let target = MeshRaycast {
161 geometry: &self.geometry,
162 side: self.material.as_ref().map_or(Side::Front, |m| m.side),
163 matrix_world: *matrix_world,
164 draw_start: self.geometry.draw_range.start,
165 draw_count: self.geometry.draw_range.count,
166 vertex_position: &|index| self.get_vertex_position(index),
167 };
168 // `geometry.boundingBox` is `null` unless the app computed it, and
169 // `computeBoundingSphere()` does not; the port's geometry cache always
170 // holds both, so reading it would add a test three.js skips. Leave it
171 // out, as in the common three.js case.
172 target.raycast(&sphere, None, object, raycaster, intersects);
173 }
174}
175
176/// `Mesh.getVertexPosition()` over any geometry and morph weights — shared by
177/// `Mesh`, and by `SkinnedMesh` before it applies the bones.
178///
179/// Zero weights are skipped, as three.js does, so an unused target costs
180/// nothing and cannot inject a `NaN`.
181pub(crate) fn vertex_position(
182 geometry: &BufferGeometry,
183 morph_target_influences: &[f64],
184 index: usize,
185) -> Vector3 {
186 let Some(position) = geometry.position() else {
187 return Vector3::ZERO;
188 };
189 let mut target = position.get_vector3(index);
190
191 if let Some(morph_position) = geometry.get_morph_attribute("position") {
192 if !morph_target_influences.is_empty() {
193 let mut morph = Vector3::ZERO;
194 for (morph_attribute, &influence) in morph_position.iter().zip(morph_target_influences)
195 {
196 if influence == 0.0 {
197 continue;
198 }
199 let mut temp = morph_attribute.get_vector3(index);
200 if geometry.morph_targets_relative {
201 morph.add_scaled_vector(&temp, influence);
202 } else {
203 temp.sub(&target);
204 morph.add_scaled_vector(&temp, influence);
205 }
206 }
207 target.add(&morph);
208 }
209 }
210 target
211}
212
213/// What `Mesh.raycast()` and `_computeIntersections()` read off `this`, pulled
214/// out so the subclasses that raycast *as* a mesh can supply their own:
215/// `InstancedMesh` and `BatchedMesh` a per-instance world matrix (three.js
216/// points a scratch `_mesh` at it), `BatchedMesh` a per-geometry draw range,
217/// `SkinnedMesh` a bone-aware vertex position.
218pub(crate) struct MeshRaycast<'a> {
219 pub geometry: &'a BufferGeometry,
220 /// `material.side`. Raycasting reads only the single `material`, so
221 /// three's `Array.isArray( material )` branch (one pass per geometry
222 /// group, each with its group's material and `materialIndex`) collapses to
223 /// the single-material loop. A [`Mesh::with_materials`] mesh is tested
224 /// front-sided over its whole draw range, and `face.materialIndex` is
225 /// always 0 (docs/nodes.md §51).
226 pub side: Side,
227 pub matrix_world: Matrix4,
228 /// `geometry.drawRange.start`.
229 pub draw_start: usize,
230 /// `geometry.drawRange.count`, `None` for `Infinity`.
231 pub draw_count: Option<usize>,
232 /// `this.getVertexPosition( index, target )`.
233 pub vertex_position: &'a dyn Fn(usize) -> Vector3,
234}
235
236impl MeshRaycast<'_> {
237 /// `Mesh.raycast()` with `geometry.boundingSphere` = `sphere` and
238 /// `geometry.boundingBox` = `bounding_box`, both in object space.
239 pub fn raycast(
240 &self,
241 sphere: &Sphere,
242 bounding_box: Option<&Box3>,
243 object: &ObjectRef,
244 raycaster: &Raycaster,
245 intersects: &mut Vec<Intersection>,
246 ) {
247 // Test with the bounding sphere in world space.
248 let mut sphere = *sphere;
249 sphere.apply_matrix4(&self.matrix_world);
250
251 // Check the distance from the ray origin to the bounding sphere.
252 let mut ray = raycaster.ray;
253 ray.recast(raycaster.near);
254 if !sphere.contains_point(&ray.origin) {
255 let Some(sphere_hit_at) = ray.intersect_sphere(&sphere) else {
256 return;
257 };
258 if ray.origin.distance_to_squared(&sphere_hit_at)
259 > (raycaster.far - raycaster.near).powi(2)
260 {
261 return;
262 }
263 }
264
265 // Convert the ray to the local space of the mesh.
266 let mut inverse_matrix = self.matrix_world;
267 inverse_matrix.invert();
268 let mut ray = raycaster.ray;
269 ray.apply_matrix4(&inverse_matrix);
270
271 // Test with the bounding box in local space.
272 if let Some(bounding_box) = bounding_box {
273 if !ray.intersects_box(bounding_box) {
274 return;
275 }
276 }
277
278 self.compute_intersections(raycaster, &ray, object, intersects);
279 }
280
281 /// `Mesh._computeIntersections( raycaster, intersects, rayLocalSpace )`.
282 pub fn compute_intersections(
283 &self,
284 raycaster: &Raycaster,
285 ray_local_space: &Ray,
286 object: &ObjectRef,
287 intersects: &mut Vec<Intersection>,
288 ) {
289 let geometry = self.geometry;
290 let draw_end = |count: usize| match self.draw_count {
291 Some(draw_count) => count.min(self.draw_start + draw_count),
292 None => count,
293 };
294
295 let mut test = |i: usize, a: usize, b: usize, c: usize| {
296 if let Some(mut intersection) =
297 self.check_geometry_intersection(raycaster, ray_local_space, a, b, c, object)
298 {
299 // The triangle number, in indexed or non-indexed semantics.
300 intersection.face_index = Some(i / 3);
301 intersects.push(intersection);
302 }
303 };
304
305 if let Some(index) = &geometry.index {
306 let start = self.draw_start;
307 let end = draw_end(index.count());
308 // A trailing partial triangle reads past the index in three.js
309 // and hits nothing (`undefined` vertices); here it is skipped.
310 let mut i = start;
311 while i < end && i + 2 < index.count() {
312 test(i, index.get_x(i), index.get_x(i + 1), index.get_x(i + 2));
313 i += 3;
314 }
315 } else if let Some(position) = geometry.position() {
316 let start = self.draw_start;
317 let end = draw_end(position.count());
318 let mut i = start;
319 while i < end && i + 2 < position.count() {
320 test(i, i, i + 1, i + 2);
321 i += 3;
322 }
323 }
324 }
325
326 /// `checkGeometryIntersection( object, material, raycaster, ray, uv, uv1,
327 /// normal, a, b, c )`.
328 fn check_geometry_intersection(
329 &self,
330 raycaster: &Raycaster,
331 ray: &Ray,
332 a: usize,
333 b: usize,
334 c: usize,
335 object: &ObjectRef,
336 ) -> Option<Intersection> {
337 let v_a = (self.vertex_position)(a);
338 let v_b = (self.vertex_position)(b);
339 let v_c = (self.vertex_position)(c);
340
341 // `checkIntersection( object, material, raycaster, ray, pA, pB, pC, point )`.
342 let point = match self.side {
343 Side::Back => ray.intersect_triangle(&v_c, &v_b, &v_a, true),
344 side => ray.intersect_triangle(&v_a, &v_b, &v_c, side == Side::Front),
345 }?;
346 let mut point_world = point;
347 point_world.apply_matrix4(&self.matrix_world);
348 let distance = raycaster.ray.origin.distance_to(&point_world);
349 if distance < raycaster.near || distance > raycaster.far {
350 return None;
351 }
352 let mut intersection = Intersection::new(distance, point_world, object.clone());
353
354 // `Triangle.getBarycoord()` leaves the target at ( 0, 0, 0 ) for a
355 // degenerate triangle, which the ray cannot have hit anyway.
356 let barycoord =
357 Triangle::static_get_barycoord(&point, &v_a, &v_b, &v_c).unwrap_or(Vector3::ZERO);
358 let geometry = self.geometry;
359 let interpolate = |name: &str| {
360 geometry.get_attribute(name).map(|attribute| {
361 Triangle::static_get_interpolated_attribute(attribute, a, b, c, &barycoord)
362 })
363 };
364 intersection.uv = interpolate("uv").map(|v| Vector2::new(v.x, v.y));
365 intersection.uv1 = interpolate("uv1").map(|v| Vector2::new(v.x, v.y));
366 intersection.normal = interpolate("normal").map(|v| {
367 let mut normal = Vector3::new(v.x, v.y, v.z);
368 if normal.dot(&ray.direction) > 0.0 {
369 normal.multiply_scalar(-1.0);
370 }
371 normal
372 });
373 intersection.face = Some(Face {
374 a,
375 b,
376 c,
377 normal: Triangle::static_get_normal(&v_a, &v_b, &v_c),
378 material_index: 0,
379 });
380 intersection.barycoord = Some(barycoord);
381 Some(intersection)
382 }
383}