three_rs/core/
object_ref.rs1use 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#[derive(Clone)]
28pub struct ObjectRef(Rc<RefCell<Object3D>>);
29
30#[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 pub fn new() -> Self {
59 Self(Weak::new())
60 }
61
62 pub fn upgrade(&self) -> Option<ObjectRef> {
64 self.0.upgrade().map(ObjectRef)
65 }
66}
67
68impl ObjectRef {
69 pub fn new(object: Object3D) -> Self {
71 Self(Rc::new(RefCell::new(object)))
72 }
73
74 pub fn ptr_eq(a: &ObjectRef, b: &ObjectRef) -> bool {
76 Rc::ptr_eq(&a.0, &b.0)
77 }
78
79 pub fn downgrade(&self) -> WeakObjectRef {
81 WeakObjectRef(Rc::downgrade(&self.0))
82 }
83
84 pub fn as_ptr(&self) -> *const RefCell<Object3D> {
89 Rc::as_ptr(&self.0)
90 }
91
92 pub fn parent(&self) -> Option<ObjectRef> {
94 self.borrow()
95 .parent
96 .as_ref()
97 .and_then(WeakObjectRef::upgrade)
98 }
99
100 pub fn children(&self) -> Vec<ObjectRef> {
103 self.borrow().children.clone()
104 }
105
106 pub fn add(&self, object: &ObjectRef) -> &Self {
108 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 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 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 pub fn clear(&self) -> &Self {
153 for child in self.children() {
154 self.remove(&child);
155 }
156
157 self
158 }
159
160 pub fn attach(&self, object: &ObjectRef) -> &Self {
162 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 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 pub fn has_event_listener(&self, ty: SceneEventType, handle: ListenerHandle) -> bool {
207 self.borrow().listeners.has(ty, handle)
208 }
209
210 pub fn remove_event_listener(&self, ty: SceneEventType, handle: ListenerHandle) {
216 self.borrow_mut().listeners.remove(ty, handle);
217 }
218
219 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 pub fn get_object_by_id(&self, id: u32) -> Option<ObjectRef> {
239 self.get_object_by_property(&|object| object.id == id)
240 }
241
242 pub fn get_object_by_name(&self, name: &str) -> Option<ObjectRef> {
244 self.get_object_by_property(&|object| object.name == name)
245 }
246
247 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 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 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 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 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 pub fn update_matrix_world(&self, force: bool) {
310 let force = update_own_matrix_world(self, force);
311
312 for child in self.children() {
314 child.update_matrix_world(force);
315 }
316 }
317
318 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 if update_children {
330 for child in self.children() {
331 update_children_world_matrix(&child, force);
332 }
333 }
334 }
335
336 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 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 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 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 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 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 pub fn look_at(&self, target: &Vector3) {
399 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 pub fn apply_matrix4(&self, m: &Matrix4) {
433 self.borrow_mut().apply_matrix4(m);
434 }
435}
436
437fn 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 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 update_bind_matrix_inverse(node);
489
490 force
491}
492
493fn 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
513fn 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}