Skip to main content

three_rs/core/
object_ref.rs

1//! The scene-graph half of `three.js/src/core/Object3D.js`: the parent/children
2//! tree and every method that needs it.
3//!
4//! See `docs/scene-graph.md` for why the tree is `Rc<RefCell<Object3D>>` with a
5//! `Weak` parent rather than an arena.
6
7use std::cell::RefCell;
8use std::ops::Deref;
9use std::rc::{Rc, Weak};
10
11use crate::core::{ListenerHandle, Object3D, SceneEvent, SceneEventType};
12use crate::math::{Matrix4, Quaternion, Vector3};
13
14/// One node of the scene graph: three.js' `Object3D` *reference*, a newtype over
15/// `Rc<RefCell<Object3D>>`.
16///
17/// Every inherent method here is the port of a three.js `Object3D` method that
18/// reads or writes `parent`/`children`; the transform-only methods stay inherent
19/// methods on [`Object3D`] itself. They live on the handle rather than on
20/// `&mut Object3D` because every one of them needs to reach outside the object
21/// it is called on — up to the parent or down into the children — which a
22/// `&mut Object3D` cannot do.
23///
24/// `ObjectRef` derefs to `RefCell<Object3D>`, so `node.borrow()` and
25/// `node.borrow_mut()` reach the object exactly as they did when `ObjectRef` was a
26/// type alias.
27#[derive(Clone)]
28pub struct ObjectRef(Rc<RefCell<Object3D>>);
29
30/// `Object3D.parent`, stored weakly so a child holding its parent does not keep
31/// the parent alive (three.js' `parent` is a strong reference, but JS has a GC
32/// and we do not).
33#[derive(Clone, Default)]
34pub struct WeakObjectRef(Weak<RefCell<Object3D>>);
35
36impl Deref for ObjectRef {
37    type Target = RefCell<Object3D>;
38
39    fn deref(&self) -> &Self::Target {
40        &self.0
41    }
42}
43
44impl std::fmt::Debug for ObjectRef {
45    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46        self.0.fmt(f)
47    }
48}
49
50impl std::fmt::Debug for WeakObjectRef {
51    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
52        self.0.fmt(f)
53    }
54}
55
56impl WeakObjectRef {
57    /// `Weak::new()` — a `WeakObjectRef` that never upgrades.
58    pub fn new() -> Self {
59        Self(Weak::new())
60    }
61
62    /// The node, if it is still alive.
63    pub fn upgrade(&self) -> Option<ObjectRef> {
64        self.0.upgrade().map(ObjectRef)
65    }
66}
67
68impl ObjectRef {
69    /// `object`, moved into a fresh scene-graph node.
70    pub fn new(object: Object3D) -> Self {
71        Self(Rc::new(RefCell::new(object)))
72    }
73
74    /// `a === b`: whether two handles are the same object. Was `Rc::ptr_eq`.
75    pub fn ptr_eq(a: &ObjectRef, b: &ObjectRef) -> bool {
76        Rc::ptr_eq(&a.0, &b.0)
77    }
78
79    /// The weak handle `Object3D.parent` holds.
80    pub fn downgrade(&self) -> WeakObjectRef {
81        WeakObjectRef(Rc::downgrade(&self.0))
82    }
83
84    /// The address of the object, for a consumer keying a cache on identity.
85    /// Note that an address is only unique among *live* nodes — see
86    /// `docs/scene-graph.md`, "Identity and eviction"; `object.id` is the
87    /// collision-free key the renderer itself uses.
88    pub fn as_ptr(&self) -> *const RefCell<Object3D> {
89        Rc::as_ptr(&self.0)
90    }
91
92    /// `Object3D.parent`, upgraded.
93    pub fn parent(&self) -> Option<ObjectRef> {
94        self.borrow()
95            .parent
96            .as_ref()
97            .and_then(WeakObjectRef::upgrade)
98    }
99
100    /// `Object3D.children`, cloned (cheap: a `Vec` of `Rc`s). Cloning is what
101    /// lets a traversal run without holding a borrow on the parent.
102    pub fn children(&self) -> Vec<ObjectRef> {
103        self.borrow().children.clone()
104    }
105
106    /// `Object3D.add( object )`.
107    pub fn add(&self, object: &ObjectRef) -> &Self {
108        // `Object3D.add: object can't be added as a child of itself.`
109        if ObjectRef::ptr_eq(self, object) {
110            return self;
111        }
112
113        object.remove_from_parent();
114        object.borrow_mut().parent = Some(self.downgrade());
115        self.borrow_mut().children.push(object.clone());
116
117        object.dispatch_event(&SceneEvent::Added);
118        self.dispatch_event(&SceneEvent::ChildAdded(object.clone()));
119
120        self
121    }
122
123    /// `Object3D.remove( object )`.
124    pub fn remove(&self, object: &ObjectRef) -> &Self {
125        let index = self
126            .borrow()
127            .children
128            .iter()
129            .position(|child| ObjectRef::ptr_eq(child, object));
130
131        if let Some(index) = index {
132            object.borrow_mut().parent = None;
133            self.borrow_mut().children.remove(index);
134
135            object.dispatch_event(&SceneEvent::Removed);
136            self.dispatch_event(&SceneEvent::ChildRemoved(object.clone()));
137        }
138
139        self
140    }
141
142    /// `Object3D.removeFromParent()`.
143    pub fn remove_from_parent(&self) -> &Self {
144        if let Some(parent) = self.parent() {
145            parent.remove(self);
146        }
147
148        self
149    }
150
151    /// `Object3D.clear()`.
152    pub fn clear(&self) -> &Self {
153        for child in self.children() {
154            self.remove(&child);
155        }
156
157        self
158    }
159
160    /// `Object3D.attach( object )`.
161    pub fn attach(&self, object: &ObjectRef) -> &Self {
162        // adds object as a child of this, while maintaining the object's world
163        // transform
164        self.update_world_matrix(true, false);
165
166        let mut m1 = self.borrow().matrix_world;
167        m1.invert();
168
169        if let Some(object_parent) = object.parent() {
170            object_parent.update_world_matrix(true, false);
171            let parent_matrix_world = object_parent.borrow().matrix_world;
172            m1.multiply(&parent_matrix_world);
173        }
174
175        object.apply_matrix4(&m1);
176
177        object.remove_from_parent();
178        object.borrow_mut().parent = Some(self.downgrade());
179        self.borrow_mut().children.push(object.clone());
180
181        object.update_world_matrix(false, true);
182
183        object.dispatch_event(&SceneEvent::Added);
184        self.dispatch_event(&SceneEvent::ChildAdded(object.clone()));
185
186        self
187    }
188
189    /// `EventDispatcher.addEventListener( type, listener )`: `listener` is
190    /// called with every event of type `ty` dispatched on this object, and
191    /// with the object itself (three's `event.target`). The returned handle
192    /// stands for the listener in [`remove_event_listener`] and
193    /// [`has_event_listener`].
194    ///
195    /// [`remove_event_listener`]: Self::remove_event_listener
196    /// [`has_event_listener`]: Self::has_event_listener
197    pub fn add_event_listener(
198        &self,
199        ty: SceneEventType,
200        listener: impl Fn(&SceneEvent, &ObjectRef) + 'static,
201    ) -> ListenerHandle {
202        self.borrow_mut().listeners.add(ty, Rc::new(listener))
203    }
204
205    /// `EventDispatcher.hasEventListener( type, listener )`.
206    pub fn has_event_listener(&self, ty: SceneEventType, handle: ListenerHandle) -> bool {
207        self.borrow().listeners.has(ty, handle)
208    }
209
210    /// `EventDispatcher.removeEventListener( type, listener )`. A handle that
211    /// is not registered for `ty` is ignored, as three ignores an unknown
212    /// listener. Safe to call from inside a listener, on itself or any other:
213    /// a dispatch already under way still calls every listener it started
214    /// with.
215    pub fn remove_event_listener(&self, ty: SceneEventType, handle: ListenerHandle) {
216        self.borrow_mut().listeners.remove(ty, handle);
217    }
218
219    /// `EventDispatcher.dispatchEvent( event )`: calls every listener of the
220    /// event's type, in the order they were added, with this node as the
221    /// target. The list is copied first and no borrow of the object is held
222    /// during the calls, so a listener may borrow the node, change the tree
223    /// (which dispatches again) or add and remove listeners.
224    pub fn dispatch_event(&self, event: &SceneEvent) {
225        let listeners = {
226            let object = self.borrow();
227            if object.listeners.is_empty() {
228                return;
229            }
230            object.listeners.snapshot(event.event_type())
231        };
232        for listener in listeners {
233            listener(event, self);
234        }
235    }
236
237    /// `Object3D.getObjectById( id )`.
238    pub fn get_object_by_id(&self, id: u32) -> Option<ObjectRef> {
239        self.get_object_by_property(&|object| object.id == id)
240    }
241
242    /// `Object3D.getObjectByName( name )`.
243    pub fn get_object_by_name(&self, name: &str) -> Option<ObjectRef> {
244        self.get_object_by_property(&|object| object.name == name)
245    }
246
247    /// `Object3D.getObjectByProperty( name, value )`. Rust has no dynamic
248    /// property lookup, so the property test is a predicate.
249    pub fn get_object_by_property(&self, test: &dyn Fn(&Object3D) -> bool) -> Option<ObjectRef> {
250        if test(&self.borrow()) {
251            return Some(self.clone());
252        }
253
254        for child in self.children() {
255            if let Some(object) = child.get_object_by_property(test) {
256                return Some(object);
257            }
258        }
259
260        None
261    }
262
263    /// `Object3D.getObjectsByProperty( name, value, result )`.
264    pub fn get_objects_by_property(&self, test: &dyn Fn(&Object3D) -> bool) -> Vec<ObjectRef> {
265        let mut result = Vec::new();
266
267        if test(&self.borrow()) {
268            result.push(self.clone());
269        }
270
271        for child in self.children() {
272            result.extend(child.get_objects_by_property(test));
273        }
274
275        result
276    }
277
278    /// `Object3D.traverse( callback )`.
279    pub fn traverse(&self, callback: &mut dyn FnMut(&ObjectRef)) {
280        callback(self);
281
282        for child in self.children() {
283            child.traverse(callback);
284        }
285    }
286
287    /// `Object3D.traverseVisible( callback )`.
288    pub fn traverse_visible(&self, callback: &mut dyn FnMut(&ObjectRef)) {
289        if !self.borrow().visible {
290            return;
291        }
292
293        callback(self);
294
295        for child in self.children() {
296            child.traverse_visible(callback);
297        }
298    }
299
300    /// `Object3D.traverseAncestors( callback )`.
301    pub fn traverse_ancestors(&self, callback: &mut dyn FnMut(&ObjectRef)) {
302        if let Some(parent) = self.parent() {
303            callback(&parent);
304            parent.traverse_ancestors(callback);
305        }
306    }
307
308    /// `Object3D.updateMatrixWorld( force )`.
309    pub fn update_matrix_world(&self, force: bool) {
310        let force = update_own_matrix_world(self, force);
311
312        // make sure descendants are updated if required
313        for child in self.children() {
314            child.update_matrix_world(force);
315        }
316    }
317
318    /// `Object3D.updateWorldMatrix( updateParents, updateChildren )`.
319    pub fn update_world_matrix(&self, update_parents: bool, update_children: bool) {
320        if update_parents {
321            if let Some(parent) = self.parent() {
322                parent.update_world_matrix(true, false);
323            }
324        }
325
326        let force = update_own_matrix_world(self, false);
327
328        // make sure descendants are updated
329        if update_children {
330            for child in self.children() {
331                update_children_world_matrix(&child, force);
332            }
333        }
334    }
335
336    /// `Object3D.getWorldPosition( target )`.
337    pub fn get_world_position(&self) -> Vector3 {
338        self.update_world_matrix(true, false);
339
340        let mut target = Vector3::ZERO;
341        target.set_from_matrix_position(&self.borrow().matrix_world);
342        target
343    }
344
345    /// `Object3D.getWorldQuaternion( target )`.
346    pub fn get_world_quaternion(&self) -> Quaternion {
347        self.update_world_matrix(true, false);
348
349        let mut position = Vector3::ZERO;
350        let mut target = Quaternion::default();
351        let mut scale = Vector3::ZERO;
352        self.borrow()
353            .matrix_world
354            .decompose(&mut position, &mut target, &mut scale);
355        target
356    }
357
358    /// `Object3D.getWorldScale( target )`.
359    pub fn get_world_scale(&self) -> Vector3 {
360        self.update_world_matrix(true, false);
361
362        let mut position = Vector3::ZERO;
363        let mut quaternion = Quaternion::default();
364        let mut target = Vector3::ZERO;
365        self.borrow()
366            .matrix_world
367            .decompose(&mut position, &mut quaternion, &mut target);
368        target
369    }
370
371    /// `Object3D.getWorldDirection( target )`.
372    pub fn get_world_direction(&self) -> Vector3 {
373        self.update_world_matrix(true, false);
374
375        let object = self.borrow();
376        let e = &object.matrix_world.elements;
377        let mut target = Vector3::new(e[8], e[9], e[10]);
378        target.normalize();
379        target
380    }
381
382    /// `Object3D.localToWorld( vector )`.
383    pub fn local_to_world(&self, vector: &mut Vector3) {
384        self.update_world_matrix(true, false);
385        vector.apply_matrix4(&self.borrow().matrix_world);
386    }
387
388    /// `Object3D.worldToLocal( vector )`.
389    pub fn world_to_local(&self, vector: &mut Vector3) {
390        self.update_world_matrix(true, false);
391
392        let mut m1 = self.borrow().matrix_world;
393        m1.invert();
394        vector.apply_matrix4(&m1);
395    }
396
397    /// `Object3D.lookAt( vector )`, parent rotation included.
398    pub fn look_at(&self, target: &Vector3) {
399        // This method does not support objects having non-uniformly-scaled
400        // parent(s)
401        let parent = self.parent();
402
403        self.update_world_matrix(true, false);
404
405        let mut position = Vector3::ZERO;
406        position.set_from_matrix_position(&self.borrow().matrix_world);
407
408        let mut m1 = Matrix4::identity();
409        let up = self.borrow().up;
410
411        if self.borrow().is_camera || self.borrow().is_light {
412            m1.look_at(&position, target, &up);
413        } else {
414            m1.look_at(target, &position, &up);
415        }
416
417        self.borrow_mut().quaternion.set_from_rotation_matrix(&m1);
418
419        if let Some(parent) = parent {
420            m1.extract_rotation(&parent.borrow().matrix_world);
421            let mut q1 = Quaternion::default();
422            q1.set_from_rotation_matrix(&m1);
423            q1.invert();
424            self.borrow_mut().quaternion.premultiply(&q1);
425        }
426
427        self.borrow_mut().sync_rotation_from_quaternion();
428    }
429
430    /// `Object3D.applyMatrix4( matrix )` — the inherent method, reached through
431    /// the cell so `attach()` can use it.
432    pub fn apply_matrix4(&self, m: &Matrix4) {
433        self.borrow_mut().apply_matrix4(m);
434    }
435}
436
437/// The `updateWorldMatrix`/`updateMatrixWorld` body both methods share: compose
438/// the local matrix, then multiply the parent's world matrix into it. Returns
439/// the new `force` for the children.
440fn update_own_matrix_world(node: &ObjectRef, force: bool) -> bool {
441    if node.borrow().matrix_auto_update {
442        node.borrow_mut().update_matrix();
443    }
444
445    // `this.matrix` *is* another object's `matrixWorld` (`CameraHelper`):
446    // read it now, as the multiply below would read the shared object.
447    let alias = node
448        .borrow()
449        .matrix_alias
450        .as_ref()
451        .and_then(WeakObjectRef::upgrade);
452    if let Some(source) = alias {
453        let matrix_world = source.borrow().matrix_world;
454        node.borrow_mut().matrix = matrix_world;
455    }
456
457    let (needs_update, world_auto_update) = {
458        let object = node.borrow();
459        (
460            object.matrix_world_needs_update,
461            object.matrix_world_auto_update,
462        )
463    };
464
465    if needs_update || force {
466        if world_auto_update {
467            let parent_matrix_world = node.parent().map(|parent| parent.borrow().matrix_world);
468            let mut object = node.borrow_mut();
469            match parent_matrix_world {
470                None => object.matrix_world = object.matrix,
471                Some(parent) => {
472                    let matrix = object.matrix;
473                    object.matrix_world.multiply_matrices(&parent, &matrix);
474                }
475            }
476        }
477
478        node.borrow_mut().matrix_world_needs_update = false;
479
480        update_bind_matrix_inverse(node);
481
482        return true;
483    }
484
485    // `SkinnedMesh.updateMatrixWorld()` calls `super.updateMatrixWorld()` and
486    // then always recomputes `bindMatrixInverse`, whether or not the world
487    // matrix was rebuilt.
488    update_bind_matrix_inverse(node);
489
490    force
491}
492
493/// The tail of `SkinnedMesh.updateMatrixWorld()`, for whichever nodes carry a
494/// `SkinnedMesh` payload. In three.js this is an override on the subclass; here
495/// the subclass is a payload variant, so the one tree walk runs it.
496///
497/// It matters that it runs *every* frame: in the default `AttachedBindMode`
498/// `bindMatrixInverse` is `matrixWorld⁻¹`, and `GLTFLoader` binds with the
499/// identity bind matrix, so everything the skin's own node contributes — a
500/// glTF `Character` node's 0.01 scale and ±90° rotation, say — lives there and
501/// nowhere else.
502fn update_bind_matrix_inverse(node: &ObjectRef) {
503    let mut object = node.borrow_mut();
504    if !object.payload.is_skinned_mesh() {
505        return;
506    }
507    let matrix_world = object.matrix_world;
508    if let Some(skin) = object.payload.skinned_mesh_mut() {
509        skin.update_bind_matrix_inverse(&matrix_world);
510    }
511}
512
513/// `updateWorldMatrix( false, true, force )` — the recursive child half, which
514/// differs from the public method only in that it threads `force` through.
515fn update_children_world_matrix(node: &ObjectRef, force: bool) {
516    let force = update_own_matrix_world(node, force);
517
518    for child in node.children() {
519        update_children_world_matrix(&child, force);
520    }
521}