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