three-rs 0.2.0

A port of three.js core and its WebGPURenderer to Rust on wgpu, graded against three.js's own end-to-end pixel comparison.
Documentation
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
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
//! Port of `three.js/src/core/Object3D.js`. The parent/children tree and the
//! methods that need it live in [`crate::core::node`]; this file is the object
//! itself and its transform methods.

use std::cell::Cell;
use std::rc::Rc;

use crate::core::node::{Node, WeakNode};
use crate::core::Layers;
use crate::math::{Euler, Matrix4, Quaternion, Vector3};
use crate::objects::{InstancedBufferAttribute, Mesh, Payload};

/// three.js' module-level `let _object3DId = 0`.
fn next_id() -> u32 {
    thread_local! {
        static OBJECT3D_ID: Cell<u32> = const { Cell::new(0) };
    }

    OBJECT3D_ID.with(|id| {
        let value = id.get();
        id.set(value + 1);
        value
    })
}

/// three.js' `Object3D`: the transform and the drawable state every scene node
/// carries. The parent/children tree lives on [`Node`], the handle that wraps
/// this in an `Rc<RefCell<..>>` — see `docs/scene-graph.md`.
#[derive(Debug)]
pub struct Object3D {
    /// `Object3D.id` — a per-thread counter, three.js' `_object3DId ++`.
    pub id: u32,
    /// `Object3D.name`.
    pub name: String,
    /// `Object3D.type`. `'Object3D'` unless a subclass overrides it (`Group`
    /// sets `'Group'`).
    pub object_type: &'static str,
    /// `Object3D.parent`, weak: see `docs/scene-graph.md`.
    pub parent: Option<WeakNode>,
    /// `Object3D.children`.
    pub children: Vec<Node>,
    /// `Object3D.visible`.
    pub visible: bool,
    /// `Object3D.layers` — tested against the camera's in `_projectObject`.
    pub layers: Layers,
    /// `Object3D.renderOrder`. On a `Group` it becomes the `groupOrder` of
    /// everything below it; on a drawable it is the second render-list sort key.
    pub render_order: f64,
    /// `Object3D.frustumCulled`.
    pub frustum_culled: bool,
    /// `Object3D.matrixAutoUpdate` (`Object3D.DEFAULT_MATRIX_AUTO_UPDATE`).
    pub matrix_auto_update: bool,
    /// `Object3D.matrixWorldAutoUpdate` (`DEFAULT_MATRIX_WORLD_AUTO_UPDATE`).
    pub matrix_world_auto_update: bool,
    /// `Object3D.matrixWorldNeedsUpdate`.
    pub matrix_world_needs_update: bool,
    /// `this.matrix = other.matrixWorld` — `CameraHelper`'s sharing of its
    /// camera's world matrix *object*. JS aliases the two; the port copies the
    /// other node's `matrix_world` into `matrix` at the moment
    /// `updateMatrixWorld()` reads `matrix`, which is when the alias would be
    /// observed. `None` for everything else, and for a clone (`copy()` copies
    /// the matrix's values, not the object).
    pub matrix_alias: Option<crate::core::WeakNode>,
    /// `Object3D.isCamera` — `lookAt()` points a camera the other way round.
    pub is_camera: bool,
    /// `Object3D.isLight` — as `is_camera`.
    pub is_light: bool,
    /// `Object3D.castShadow` — whether the shadow pass draws this object.
    pub cast_shadow: bool,
    /// `Object3D.receiveShadow` — whether the object's material samples the
    /// shadow maps, which makes it a different program from the same material
    /// on a non-receiving object.
    pub receive_shadow: bool,
    /// `object.occlusionTest` — not a declared `Object3D` property in three
    /// but an ad-hoc one the renderer reads (`RenderList.push()`,
    /// `WebGPUBackend.draw()`): when `true` the object's draws are wrapped in
    /// an occlusion query, and `renderer.isOccluded( object )` answers from its
    /// result. Being ad hoc, `Object3D.copy()` does not carry it, so neither
    /// does [`Clone`].
    pub occlusion_test: bool,
    /// `Object3D.isGroup`.
    pub is_group: bool,
    /// `Object3D.isScene`.
    pub is_scene: bool,
    /// `Object3D.position`.
    pub position: Vector3,
    /// Kept in sync with `quaternion` by [`Object3D::set_rotation`], the same way
    /// three.js' `Euler`/`Quaternion` `onChange` callbacks keep them in sync.
    pub rotation: Euler,
    /// `Object3D.quaternion`.
    pub quaternion: Quaternion,
    /// `Object3D.scale`.
    pub scale: Vector3,
    /// `Object3D.up`.
    pub up: Vector3,
    /// `Object3D.matrix`, composed from `position`/`quaternion`/`scale` by
    /// [`update_matrix`](Self::update_matrix).
    pub matrix: Matrix4,
    /// `Object3D.matrixWorld`.
    pub matrix_world: Matrix4,
    /// `Object3D.userData` — the application's own data on the object, an
    /// open JSON object as in three.js. The node system reads it through
    /// [`user_data`](crate::nodes::tsl::user_data), once per draw, as
    /// `UserDataNode` does.
    pub user_data: serde_json::Map<String, serde_json::Value>,
    /// What three.js would get from subclassing: the `Mesh`/`InstancedMesh`
    /// state that makes this node drawable. See [`Payload`].
    pub payload: Payload,
}

impl Default for Object3D {
    fn default() -> Self {
        Self {
            id: next_id(),
            name: String::new(),
            object_type: "Object3D",
            parent: None,
            children: Vec::new(),
            visible: true,
            layers: Layers::default(),
            render_order: 0.0,
            frustum_culled: true,
            matrix_auto_update: true,
            matrix_world_auto_update: true,
            matrix_world_needs_update: false,
            matrix_alias: None,
            is_camera: false,
            is_light: false,
            cast_shadow: false,
            receive_shadow: false,
            occlusion_test: false,
            is_group: false,
            is_scene: false,
            position: Vector3::ZERO,
            rotation: Euler::default(),
            quaternion: Quaternion::default(),
            scale: Vector3::new(1.0, 1.0, 1.0),
            // `Object3D.DEFAULT_UP`
            up: Vector3::new(0.0, 1.0, 0.0),
            matrix: Matrix4::identity(),
            matrix_world: Matrix4::identity(),
            user_data: serde_json::Map::new(),
            payload: Payload::None,
        }
    }
}

/// `Object3D.copy( source, recursive = false )`, minus the tree: a clone gets a
/// fresh `id` and no parent or children, because a `Clone` that shared the
/// `Rc`s would give two objects the same child list.
impl Clone for Object3D {
    fn clone(&self) -> Self {
        Self {
            id: next_id(),
            name: self.name.clone(),
            object_type: self.object_type,
            parent: None,
            children: Vec::new(),
            visible: self.visible,
            layers: self.layers,
            render_order: self.render_order,
            frustum_culled: self.frustum_culled,
            matrix_auto_update: self.matrix_auto_update,
            matrix_world_auto_update: self.matrix_world_auto_update,
            matrix_world_needs_update: self.matrix_world_needs_update,
            matrix_alias: None,
            is_camera: self.is_camera,
            is_light: self.is_light,
            cast_shadow: self.cast_shadow,
            receive_shadow: self.receive_shadow,
            occlusion_test: false,
            is_group: self.is_group,
            is_scene: self.is_scene,
            position: self.position,
            rotation: self.rotation,
            quaternion: self.quaternion,
            scale: self.scale,
            up: self.up,
            matrix: self.matrix,
            matrix_world: self.matrix_world,
            // `JSON.parse( JSON.stringify( source.userData ) )`: a deep copy.
            user_data: self.user_data.clone(),
            payload: self.payload.clone(),
        }
    }
}

impl Object3D {
    /// A fresh `Object3D` as a scene-graph [`Node`].
    pub fn new_node() -> Node {
        Node::new(Self::default())
    }

    /// This object, moved into a scene-graph [`Node`].
    pub fn into_node(self) -> Node {
        Node::new(self)
    }

    /// `object.isMesh` — see [`Payload::is_mesh`].
    pub fn is_mesh(&self) -> bool {
        self.payload.is_mesh()
    }

    /// `object.isSkinnedMesh`.
    pub fn is_skinned_mesh(&self) -> bool {
        self.payload.is_skinned_mesh()
    }

    /// The `SkinnedMesh` this object is, if it is one.
    pub fn skinned_mesh(&self) -> Option<&crate::objects::SkinnedMesh> {
        self.payload.skinned_mesh()
    }

    /// `object.isSkinnedMesh`'s `SkinnedMesh` state, mutably.
    pub fn skinned_mesh_mut(&mut self) -> Option<&mut crate::objects::SkinnedMesh> {
        self.payload.skinned_mesh_mut()
    }

    /// `object.isInstancedMesh`.
    pub fn is_instanced_mesh(&self) -> bool {
        self.payload.is_instanced_mesh()
    }

    /// `object.isLine` — see [`Payload::is_line`].
    pub fn is_line(&self) -> bool {
        self.payload.is_line()
    }

    /// `object.isPoints` — see [`Payload::is_points`].
    pub fn is_points(&self) -> bool {
        self.payload.is_points()
    }

    /// `object.isLineSegments`.
    pub fn is_line_segments(&self) -> bool {
        self.payload.is_line_segments()
    }

    /// `Line.geometry` / `Line.material` when this node is a line.
    pub fn line(&self) -> Option<&crate::objects::Line> {
        self.payload.line()
    }

    /// `Line.geometry` / `Line.material`, mutably, when this node is a line.
    pub fn line_mut(&mut self) -> Option<&mut crate::objects::Line> {
        self.payload.line_mut()
    }

    /// `object.geometry` for a mesh or a line.
    pub fn geometry(&self) -> Option<&Rc<crate::core::BufferGeometry>> {
        self.payload.geometry()
    }

    /// `object.material` for a mesh or a line.
    pub fn material(&self) -> Option<&crate::materials::MeshBasicNodeMaterial> {
        self.payload.material()
    }

    /// `Mesh.geometry` / `Mesh.material` when this node is a mesh.
    pub fn mesh(&self) -> Option<&Mesh> {
        self.payload.mesh()
    }

    /// `Mesh.geometry` / `Mesh.material`, mutably, when this node is a mesh.
    pub fn mesh_mut(&mut self) -> Option<&mut Mesh> {
        self.payload.mesh_mut()
    }

    /// The light state when `is_light` is true — `Light.color`,
    /// `Light.intensity`, `PointLight.distance`, `PointLight.decay`.
    pub fn light(&self) -> Option<&crate::lights::LightObject> {
        self.payload.light()
    }

    /// The light state, mutably; see [`light`](Self::light).
    pub fn light_mut(&mut self) -> Option<&mut crate::lights::LightObject> {
        self.payload.light_mut()
    }

    /// `InstancedMesh.count`, else 1.
    pub(crate) fn instance_count(&self) -> u32 {
        self.payload.count()
    }

    /// `InstancedMesh.instanceMatrix`.
    pub fn instance_matrix(&self) -> Option<&InstancedBufferAttribute> {
        self.payload.instance_matrix()
    }

    /// `InstancedMesh.instanceColor`, `None` until `setColorAt()` is called.
    pub fn instance_color(&self) -> Option<&InstancedBufferAttribute> {
        self.payload.instance_color()
    }

    /// `InstancedMesh.setMatrixAt( index, matrix )`, reached through the payload.
    ///
    /// Panics if this node is not an `InstancedMesh`, the way the JS would throw.
    pub fn set_matrix_at(&mut self, index: usize, matrix: &Matrix4) {
        self.payload
            .instanced_mesh_mut()
            .expect("three-rs: setMatrixAt on an object that is not an InstancedMesh")
            .set_matrix_at(index, matrix);
    }

    /// `InstancedMesh.setColorAt( index, color )`, reached through the payload.
    ///
    /// Panics if this node is not an `InstancedMesh`, the way the JS would throw.
    pub fn set_color_at(&mut self, index: usize, color: &crate::math::Color) {
        self.payload
            .instanced_mesh_mut()
            .expect("three-rs: setColorAt on an object that is not an InstancedMesh")
            .set_color_at(index, color);
    }

    /// `object.rotation.set( x, y, z )` — the Euler `onChange` callback then
    /// refreshes the quaternion, which is what `updateMatrix()` composes from.
    pub fn set_rotation(&mut self, x: f64, y: f64, z: f64) {
        self.rotation.set(x, y, z);
        self.quaternion.set_from_euler(&self.rotation);
    }

    /// three.js' `Quaternion.onChange` callback: keeps `rotation` in step with
    /// `quaternion` (`rotation.setFromQuaternion( quaternion, rotation.order,
    /// false )`). Every method below that writes the quaternion calls this, the
    /// way three.js' property setters do.
    pub(crate) fn sync_rotation_from_quaternion(&mut self) {
        let (q, order) = (self.quaternion, self.rotation.order);
        self.rotation.set_from_quaternion(&q, order);
    }

    /// `Object3D.applyMatrix4()`.
    pub fn apply_matrix4(&mut self, m: &Matrix4) {
        if self.matrix_auto_update {
            self.update_matrix();
        }

        self.matrix.premultiply(m);

        let matrix = self.matrix;
        let (mut position, mut quaternion, mut scale) =
            (self.position, self.quaternion, self.scale);
        matrix.decompose(&mut position, &mut quaternion, &mut scale);
        self.position = position;
        self.quaternion = quaternion;
        self.scale = scale;

        self.sync_rotation_from_quaternion();
    }

    /// `Object3D.applyQuaternion()`.
    pub fn apply_quaternion(&mut self, q: &Quaternion) {
        self.quaternion.premultiply(q);
        self.sync_rotation_from_quaternion();
    }

    /// `Object3D.setRotationFromAxisAngle()`.
    pub fn set_rotation_from_axis_angle(&mut self, axis: &Vector3, angle: f64) {
        // assumes axis is normalized
        self.quaternion.set_from_axis_angle(axis, angle);
        self.sync_rotation_from_quaternion();
    }

    /// `Object3D.setRotationFromEuler()`.
    pub fn set_rotation_from_euler(&mut self, euler: &Euler) {
        self.quaternion.set_from_euler(euler);
        self.sync_rotation_from_quaternion();
    }

    /// `Object3D.setRotationFromMatrix()` — the upper 3x3 of `m` must be a pure
    /// rotation (unscaled).
    pub fn set_rotation_from_matrix(&mut self, m: &Matrix4) {
        self.quaternion.set_from_rotation_matrix(m);
        self.sync_rotation_from_quaternion();
    }

    /// `Object3D.setRotationFromQuaternion()` — `q` is assumed normalized.
    pub fn set_rotation_from_quaternion(&mut self, q: &Quaternion) {
        self.quaternion.copy(q);
        self.sync_rotation_from_quaternion();
    }

    /// `Object3D.rotateOnAxis()` — rotates about an axis in object space.
    pub fn rotate_on_axis(&mut self, axis: &Vector3, angle: f64) {
        let mut q1 = Quaternion::default();
        q1.set_from_axis_angle(axis, angle);

        self.quaternion.multiply(&q1);
        self.sync_rotation_from_quaternion();
    }

    /// `Object3D.rotateOnWorldAxis()` — rotates about an axis in world space.
    /// Assumes the object has no rotated parent.
    pub fn rotate_on_world_axis(&mut self, axis: &Vector3, angle: f64) {
        let mut q1 = Quaternion::default();
        q1.set_from_axis_angle(axis, angle);

        self.quaternion.premultiply(&q1);
        self.sync_rotation_from_quaternion();
    }

    /// `Object3D.rotateX()`.
    pub fn rotate_x(&mut self, angle: f64) {
        self.rotate_on_axis(&Vector3::new(1.0, 0.0, 0.0), angle);
    }

    /// `Object3D.rotateY()`.
    pub fn rotate_y(&mut self, angle: f64) {
        self.rotate_on_axis(&Vector3::new(0.0, 1.0, 0.0), angle);
    }

    /// `Object3D.rotateZ()`.
    pub fn rotate_z(&mut self, angle: f64) {
        self.rotate_on_axis(&Vector3::new(0.0, 0.0, 1.0), angle);
    }

    /// `Object3D.translateOnAxis()` — translates along an axis in object space.
    pub fn translate_on_axis(&mut self, axis: &Vector3, distance: f64) {
        let mut v1 = *axis;
        v1.apply_quaternion(&self.quaternion);
        v1.multiply_scalar(distance);

        self.position.add(&v1);
    }

    /// `Object3D.translateX()`.
    pub fn translate_x(&mut self, distance: f64) {
        self.translate_on_axis(&Vector3::new(1.0, 0.0, 0.0), distance);
    }

    /// `Object3D.translateY()`.
    pub fn translate_y(&mut self, distance: f64) {
        self.translate_on_axis(&Vector3::new(0.0, 1.0, 0.0), distance);
    }

    /// `Object3D.translateZ()`.
    pub fn translate_z(&mut self, distance: f64) {
        self.translate_on_axis(&Vector3::new(0.0, 0.0, 1.0), distance);
    }

    /// `Object3D.localToWorld()`.
    pub fn local_to_world(&mut self, vector: &mut Vector3) {
        self.update_matrix_world(None);
        vector.apply_matrix4(&self.matrix_world);
    }

    /// `Object3D.worldToLocal()`.
    pub fn world_to_local(&mut self, vector: &mut Vector3) {
        self.update_matrix_world(None);

        let mut inverse = self.matrix_world;
        inverse.invert();
        vector.apply_matrix4(&inverse);
    }

    /// `Object3D.lookAt()` for a plain object: the object's +Z is pointed away
    /// from `target` (a camera or light points *at* it instead — see
    /// `PerspectiveCamera::look_at`).
    pub fn look_at(&mut self, target: &Vector3) {
        self.update_matrix_world(None);

        let mut position = Vector3::ZERO;
        position.set_from_matrix_position(&self.matrix_world);

        let mut m1 = Matrix4::identity();
        m1.look_at(target, &position, &self.up);

        self.quaternion.set_from_rotation_matrix(&m1);
        self.sync_rotation_from_quaternion();
    }

    /// `Object3D.getWorldPosition()`.
    pub fn get_world_position(&mut self) -> Vector3 {
        self.update_matrix_world(None);

        let mut target = Vector3::ZERO;
        target.set_from_matrix_position(&self.matrix_world);
        target
    }

    /// `Object3D.getWorldQuaternion()`.
    pub fn get_world_quaternion(&mut self) -> Quaternion {
        self.update_matrix_world(None);

        let mut position = Vector3::ZERO;
        let mut target = Quaternion::default();
        let mut scale = Vector3::ZERO;
        self.matrix_world
            .decompose(&mut position, &mut target, &mut scale);
        target
    }

    /// `Object3D.getWorldScale()`.
    pub fn get_world_scale(&mut self) -> Vector3 {
        self.update_matrix_world(None);

        let mut position = Vector3::ZERO;
        let mut quaternion = Quaternion::default();
        let mut target = Vector3::ZERO;
        self.matrix_world
            .decompose(&mut position, &mut quaternion, &mut target);
        target
    }

    /// `Object3D.getWorldDirection()` — the object's +Z axis in world space.
    pub fn get_world_direction(&mut self) -> Vector3 {
        self.update_matrix_world(None);

        let e = &self.matrix_world.elements;
        let mut target = Vector3::new(e[8], e[9], e[10]);
        target.normalize();
        target
    }

    /// `Object3D.updateMatrix()`.
    pub fn update_matrix(&mut self) {
        let (position, quaternion, scale) = (self.position, self.quaternion, self.scale);
        self.matrix.compose(&position, &quaternion, &scale);

        self.matrix_world_needs_update = true;
    }

    /// `Object3D.updateMatrixWorld()` for an object whose parent's world matrix
    /// is `parent_matrix_world` (`None` for a root).
    pub fn update_matrix_world(&mut self, parent_matrix_world: Option<&Matrix4>) {
        self.update_matrix_world_forced(parent_matrix_world, false);
    }

    /// `Object3D.updateMatrixWorld( force )` for one object, returning the
    /// `force` its children should be updated with (three.js recurses here; an
    /// `Object3D` held by value has no children to recurse into, so the caller
    /// — `Scene::update_matrix_world`, or `Node`'s tree methods — does
    /// that part).
    pub(crate) fn update_matrix_world_forced(
        &mut self,
        parent_matrix_world: Option<&Matrix4>,
        force: bool,
    ) -> bool {
        if self.matrix_auto_update {
            self.update_matrix();
        }

        if self.matrix_world_needs_update || force {
            if self.matrix_world_auto_update {
                match parent_matrix_world {
                    None => self.matrix_world = self.matrix,
                    Some(parent) => {
                        let matrix = self.matrix;
                        self.matrix_world.multiply_matrices(parent, &matrix);
                    }
                }
            }

            self.matrix_world_needs_update = false;

            return true;
        }

        force
    }
}