1#![allow(clippy::type_complexity)]
22
23pub mod constructor;
26
27pub mod prelude {
28 pub use crate::SceneGraph;
29}
30
31use fxhash::FxHashMap;
32use fyrox_core::pool::{ObjectOrVariant, PayloadContainer, PoolError};
33use fyrox_core::reflect::ReflectHandle;
34use fyrox_core::{
35 log::{Log, MessageKind},
36 pool::Handle,
37 reflect::prelude::*,
38 variable::{self, InheritableVariable},
39 ComponentProvider, NameProvider, Uuid,
40};
41use fyrox_resource::{untyped::UntypedResource, Resource, TypedResourceData};
42use std::any::Any;
43use std::cmp::Ordering;
44use std::fmt::{Debug, Formatter};
45use std::{
46 any::TypeId,
47 ops::{Deref, DerefMut},
48};
49
50#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Reflect)]
51#[repr(u32)]
52pub enum NodeMapping {
53 UseNames = 0,
54 UseHandles = 1,
55}
56
57pub struct NodeHandleMap<N> {
69 pub(crate) map: FxHashMap<Handle<N>, Handle<N>>,
70}
71
72impl<N> Debug for NodeHandleMap<N> {
73 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
74 for (from, to) in self.map.iter() {
75 writeln!(f, "{from} -> {to}")?;
76 }
77 Ok(())
78 }
79}
80
81impl<N> Default for NodeHandleMap<N> {
82 fn default() -> Self {
83 Self {
84 map: Default::default(),
85 }
86 }
87}
88
89impl<N> Clone for NodeHandleMap<N> {
90 fn clone(&self) -> Self {
91 Self {
92 map: self.map.clone(),
93 }
94 }
95}
96
97impl<N> NodeHandleMap<N>
98where
99 N: Reflect + NameProvider,
100{
101 #[inline]
103 pub fn insert(
104 &mut self,
105 original_handle: Handle<N>,
106 copy_handle: Handle<N>,
107 ) -> Option<Handle<N>> {
108 self.map.insert(original_handle, copy_handle)
109 }
110
111 #[inline]
114 pub fn map(&self, handle: &mut Handle<N>) -> &Self {
115 *handle = self.map.get(handle).cloned().unwrap_or_default();
116 self
117 }
118
119 #[inline]
122 pub fn map_slice<T>(&self, handles: &mut [T]) -> &Self
123 where
124 T: Deref<Target = Handle<N>> + DerefMut,
125 {
126 for handle in handles {
127 self.map(handle);
128 }
129 self
130 }
131
132 #[inline]
135 pub fn try_map(&self, handle: &mut Handle<N>) -> bool {
136 if let Some(new_handle) = self.map.get(handle) {
137 *handle = *new_handle;
138 true
139 } else {
140 false
141 }
142 }
143
144 #[inline]
147 pub fn try_map_reflect(&self, reflect_handle: &mut dyn ReflectHandle) -> bool {
148 let handle = Handle::new(
149 reflect_handle.reflect_index(),
150 reflect_handle.reflect_generation(),
151 );
152 if let Some(new_handle) = self.map.get(&handle) {
153 reflect_handle.reflect_set_index(new_handle.index());
154 reflect_handle.reflect_set_generation(new_handle.generation());
155 true
156 } else {
157 false
158 }
159 }
160
161 #[inline]
164 pub fn try_map_slice<T>(&self, handles: &mut [T]) -> bool
165 where
166 T: Deref<Target = Handle<N>> + DerefMut,
167 {
168 let mut success = true;
169 for handle in handles {
170 success &= self.try_map(handle);
171 }
172 success
173 }
174
175 #[inline]
179 pub fn try_map_silent(&self, inheritable_handle: &mut InheritableVariable<Handle<N>>) -> bool {
180 if let Some(new_handle) = self.map.get(inheritable_handle) {
181 inheritable_handle.set_value_silent(*new_handle);
182 true
183 } else {
184 false
185 }
186 }
187
188 #[inline]
190 pub fn inner(&self) -> &FxHashMap<Handle<N>, Handle<N>> {
191 &self.map
192 }
193
194 #[inline]
196 pub fn into_inner(self) -> FxHashMap<Handle<N>, Handle<N>> {
197 self.map
198 }
199
200 #[inline]
204 pub fn remap_handles(&self, node: &mut N, ignored_types: &[TypeId]) {
205 let name = node.name().to_string();
206 node.as_reflect_mut(&mut |node| self.remap_handles_any(node, &name, ignored_types));
207 }
208
209 pub fn remap_handles_any(
210 &self,
211 entity: &mut dyn Reflect,
212 node_name: &str,
213 ignored_types: &[TypeId],
214 ) {
215 if ignored_types.contains(&(*entity).type_id()) {
216 return;
217 }
218
219 let mut mapped = false;
220
221 entity.downcast_mut::<Handle<N>>(&mut |handle| {
222 if let Some(handle) = handle {
223 if handle.is_some() && !self.try_map(handle) {
224 Log::warn(format!(
225 "Failed to remap handle {} of node {}!",
226 *handle, node_name
227 ));
228 }
229 mapped = true;
230 }
231 });
232
233 if mapped {
234 return;
235 }
236
237 entity.as_handle_mut(&mut |handle| {
239 if let Some(handle) = handle {
240 if handle.query_derived_types().contains(&TypeId::of::<N>())
241 && handle.reflect_is_some()
242 && !self.try_map_reflect(handle)
243 {
244 Log::warn(format!(
245 "Failed to remap handle {}:{} of node {}!",
246 handle.reflect_index(),
247 handle.reflect_generation(),
248 node_name
249 ));
250 }
251 mapped = true;
252 }
253 });
254
255 if mapped {
256 return;
257 }
258
259 entity.as_inheritable_variable_mut(&mut |inheritable| {
260 if let Some(inheritable) = inheritable {
261 self.remap_handles_any(inheritable.inner_value_mut(), node_name, ignored_types);
263
264 mapped = true;
265 }
266 });
267
268 if mapped {
269 return;
270 }
271
272 entity.as_array_mut(&mut |array| {
273 if let Some(array) = array {
274 for i in 0..array.reflect_len() {
276 if let Some(item) = array.reflect_index_mut(i) {
278 self.remap_handles_any(item, node_name, ignored_types);
279 }
280 }
281 mapped = true;
282 }
283 });
284
285 if mapped {
286 return;
287 }
288
289 entity.as_hash_map_mut(&mut |hash_map| {
290 if let Some(hash_map) = hash_map {
291 for i in 0..hash_map.reflect_len() {
292 if let Some(item) = hash_map.reflect_get_nth_value_mut(i) {
293 self.remap_handles_any(item, node_name, ignored_types);
294 }
295 }
296 mapped = true;
297 }
298 });
299
300 if mapped {
301 return;
302 }
303
304 entity.fields_mut(&mut |fields| {
306 for field_info_mut in fields {
307 field_info_mut
308 .value
309 .field_value_as_reflect_mut()
310 .as_reflect_mut(&mut |field| {
311 self.remap_handles_any(field, node_name, ignored_types)
312 })
313 }
314 })
315 }
316
317 #[inline]
318 pub fn remap_inheritable_handles(&self, node: &mut N, ignored_types: &[TypeId]) {
319 let name = node.name().to_string();
320 node.as_reflect_mut(&mut |node| {
321 self.remap_inheritable_handles_internal(node, &name, false, ignored_types)
322 });
323 }
324
325 fn remap_inheritable_handles_internal(
326 &self,
327 entity: &mut dyn Reflect,
328 node_name: &str,
329 do_map: bool,
330 ignored_types: &[TypeId],
331 ) {
332 if ignored_types.contains(&(*entity).type_id()) {
333 return;
334 }
335
336 let mut mapped = false;
337
338 entity.as_inheritable_variable_mut(&mut |result| {
339 if let Some(inheritable) = result {
340 if !inheritable.is_modified() {
342 self.remap_inheritable_handles_internal(
343 inheritable.inner_value_mut(),
344 node_name,
345 true,
348 ignored_types,
349 );
350 }
351 mapped = true;
352 }
353 });
354
355 if mapped {
356 return;
357 }
358
359 entity.downcast_mut::<Handle<N>>(&mut |result| {
360 if let Some(handle) = result {
361 if do_map && handle.is_some() && !self.try_map(handle) {
362 Log::warn(format!(
363 "Failed to remap handle {} of node {}!",
364 *handle, node_name
365 ));
366 }
367 mapped = true;
368 }
369 });
370
371 if mapped {
372 return;
373 }
374
375 entity.as_handle_mut(&mut |handle| {
377 if let Some(handle) = handle {
378 if do_map
379 && handle.query_derived_types().contains(&TypeId::of::<N>())
380 && handle.reflect_is_some()
381 && !self.try_map_reflect(handle)
382 {
383 Log::warn(format!(
384 "Failed to remap handle {}:{} of node {}!",
385 handle.reflect_index(),
386 handle.reflect_generation(),
387 node_name
388 ));
389 }
390 mapped = true;
391 }
392 });
393
394 if mapped {
395 return;
396 }
397
398 entity.as_array_mut(&mut |result| {
399 if let Some(array) = result {
400 for i in 0..array.reflect_len() {
402 if let Some(item) = array.reflect_index_mut(i) {
404 self.remap_inheritable_handles_internal(
405 item,
406 node_name,
407 do_map,
410 ignored_types,
411 );
412 }
413 }
414 mapped = true;
415 }
416 });
417
418 if mapped {
419 return;
420 }
421
422 entity.as_hash_map_mut(&mut |result| {
423 if let Some(hash_map) = result {
424 for i in 0..hash_map.reflect_len() {
425 if let Some(item) = hash_map.reflect_get_nth_value_mut(i) {
426 self.remap_inheritable_handles_internal(
427 item,
428 node_name,
429 do_map,
432 ignored_types,
433 );
434 }
435 }
436 mapped = true;
437 }
438 });
439
440 if mapped {
441 return;
442 }
443
444 entity.fields_mut(&mut |fields| {
446 for field_info_mut in fields {
447 self.remap_inheritable_handles_internal(
448 field_info_mut.value.field_value_as_reflect_mut(),
449 node_name,
450 do_map,
453 ignored_types,
454 );
455 }
456 })
457 }
458}
459
460fn reset_property_modified_flag(entity: &mut dyn Reflect, path: &str) {
461 entity.as_reflect_mut(&mut |entity| {
462 entity.resolve_path_mut(path, &mut |result| {
463 variable::mark_inheritable_properties_non_modified(
464 result.unwrap(),
465 &[TypeId::of::<UntypedResource>()],
466 );
467 })
468 })
469}
470
471pub trait SceneGraphNode: ComponentProvider + Reflect + NameProvider + Clone + 'static {
472 type Base: Clone;
473 type SceneGraph: SceneGraph<Node = Self>;
474 type ResourceData: PrefabData<Graph = Self::SceneGraph>;
475
476 fn base(&self) -> &Self::Base;
477 fn set_base(&mut self, base: Self::Base);
478 fn is_resource_instance_root(&self) -> bool;
479 fn original_handle_in_resource(&self) -> Handle<Self>;
480 fn set_original_handle_in_resource(&mut self, handle: Handle<Self>);
481 fn resource(&self) -> Option<Resource<Self::ResourceData>>;
482 fn self_handle(&self) -> Handle<Self>;
483 fn parent(&self) -> Handle<Self>;
484 fn children(&self) -> &[Handle<Self>];
485 fn children_mut(&mut self) -> &mut [Handle<Self>];
486 fn instance_id(&self) -> Uuid;
487
488 #[inline]
490 fn swap_child_position(&mut self, child: Handle<Self>, pos: usize) -> Option<usize> {
491 let children = self.children_mut();
492
493 if pos >= children.len() {
494 return None;
495 }
496
497 if let Some(current_position) = children.iter().position(|c| *c == child) {
498 children.swap(current_position, pos);
499
500 Some(current_position)
501 } else {
502 None
503 }
504 }
505
506 #[inline]
507 fn set_child_position(&mut self, child: Handle<Self>, dest_pos: usize) -> Option<usize> {
508 let children = self.children_mut();
509
510 if dest_pos >= children.len() {
511 return None;
512 }
513
514 if let Some(mut current_position) = children.iter().position(|c| *c == child) {
515 let prev_position = current_position;
516
517 match current_position.cmp(&dest_pos) {
518 Ordering::Less => {
519 while current_position != dest_pos {
520 let next = current_position.saturating_add(1);
521 children.swap(current_position, next);
522 current_position = next;
523 }
524 }
525 Ordering::Equal => {}
526 Ordering::Greater => {
527 while current_position != dest_pos {
528 let prev = current_position.saturating_sub(1);
529 children.swap(current_position, prev);
530 current_position = prev;
531 }
532 }
533 }
534
535 Some(prev_position)
536 } else {
537 None
538 }
539 }
540
541 #[inline]
542 fn child_position(&self, child: Handle<Self>) -> Option<usize> {
543 self.children().iter().position(|c| *c == child)
544 }
545
546 #[inline]
547 fn has_child(&self, child: Handle<Self>) -> bool {
548 self.children().contains(&child)
549 }
550
551 fn revert_inheritable_property(&mut self, path: &str) -> Option<Box<dyn Reflect>> {
552 let mut previous_value = None;
553
554 if let Some(resource) = self.resource().as_ref() {
556 let resource_data = resource.data_ref();
557 let parent = &resource_data
558 .graph()
559 .node(self.original_handle_in_resource());
560
561 let mut parent_value = None;
562
563 parent.as_reflect(&mut |parent| {
565 parent.resolve_path(path, &mut |result| match result {
566 Ok(parent_field) => parent_field.as_inheritable_variable(&mut |parent_field| {
567 if let Some(parent_inheritable) = parent_field {
568 parent_value = Some(parent_inheritable.clone_value_box());
569 }
570 }),
571 Err(e) => Log::err(format!(
572 "Failed to resolve parent path {path}. Reason: {e:?}"
573 )),
574 })
575 });
576
577 let mut need_revert = false;
579
580 self.as_reflect_mut(&mut |child| {
581 child.resolve_path_mut(path, &mut |result| match result {
582 Ok(child_field) => {
583 child_field.as_inheritable_variable_mut(&mut |child_inheritable| {
584 if let Some(child_inheritable) = child_inheritable {
585 need_revert = child_inheritable.is_modified();
586 } else {
587 Log::err(format!("Property {path} is not inheritable!"))
588 }
589 })
590 }
591 Err(e) => Log::err(format!(
592 "Failed to resolve child path {path}. Reason: {e:?}"
593 )),
594 });
595 });
596
597 if need_revert {
599 if let Some(parent_value) = parent_value {
600 let mut was_set = false;
601
602 let mut parent_value = Some(parent_value);
603 self.as_reflect_mut(&mut |child| {
604 child.set_field_by_path(
605 path,
606 parent_value.take().unwrap(),
607 &mut |result| match result {
608 Ok(old_value) => {
609 previous_value = Some(old_value);
610
611 was_set = true;
612 }
613 Err(_) => Log::err(format!(
614 "Failed to revert property {path}. Reason: no such property!"
615 )),
616 },
617 );
618 });
619
620 if was_set {
621 reset_property_modified_flag(self, path);
623 }
624 }
625 }
626 }
627
628 previous_value
629 }
630
631 #[inline]
633 fn component_ref<T: Any>(&self) -> Option<&T> {
634 ComponentProvider::query_component_ref(self, TypeId::of::<T>())
635 .and_then(|c| c.downcast_ref())
636 }
637
638 #[inline]
640 fn component_mut<T: Any>(&mut self) -> Option<&mut T> {
641 ComponentProvider::query_component_mut(self, TypeId::of::<T>())
642 .and_then(|c| c.downcast_mut())
643 }
644
645 #[inline]
647 fn has_component<T: Any>(&self) -> bool {
648 self.component_ref::<T>().is_some()
649 }
650}
651
652pub trait PrefabData: TypedResourceData + 'static {
653 type Graph: SceneGraph;
654
655 fn graph(&self) -> &Self::Graph;
656 fn mapping(&self) -> NodeMapping;
657}
658
659#[derive(Debug)]
660pub struct LinkScheme<N> {
661 pub root: Handle<N>,
662 pub links: Vec<(Handle<N>, Handle<N>)>,
663}
664
665impl<N> Default for LinkScheme<N> {
666 fn default() -> Self {
667 Self {
668 root: Default::default(),
669 links: Default::default(),
670 }
671 }
672}
673
674pub trait SceneGraph: 'static {
676 type Prefab: PrefabData<Graph = Self>;
677 type NodeContainer: PayloadContainer<Element = Self::Node>;
678 type Node: SceneGraphNode<SceneGraph = Self, ResourceData = Self::Prefab>;
679
680 fn summary(&self) -> String;
682
683 fn actual_type_id(&self, handle: Handle<Self::Node>) -> Result<TypeId, PoolError>;
685
686 fn actual_type_name(&self, handle: Handle<Self::Node>) -> Result<&'static str, PoolError>;
688
689 fn derived_type_ids(&self, handle: Handle<Self::Node>) -> Result<Vec<TypeId>, PoolError>;
691
692 fn root(&self) -> Handle<Self::Node>;
694
695 fn set_root(&mut self, root: Handle<Self::Node>);
697
698 fn try_get_node(&self, handle: Handle<Self::Node>) -> Result<&Self::Node, PoolError>;
700
701 fn try_get_node_mut(
703 &mut self,
704 handle: Handle<Self::Node>,
705 ) -> Result<&mut Self::Node, PoolError>;
706
707 fn is_valid_handle(&self, handle: Handle<impl ObjectOrVariant<Self::Node>>) -> bool;
709
710 fn add_node(&mut self, node: Self::Node) -> Handle<Self::Node>;
712
713 fn add_node_at_handle(&mut self, node: Self::Node, handle: Handle<Self::Node>);
715
716 fn remove_node(&mut self, node_handle: Handle<impl ObjectOrVariant<Self::Node>>);
718
719 fn link_nodes(
721 &mut self,
722 child: Handle<impl ObjectOrVariant<Self::Node>>,
723 parent: Handle<impl ObjectOrVariant<Self::Node>>,
724 );
725
726 fn unlink_node(&mut self, node_handle: Handle<impl ObjectOrVariant<Self::Node>>);
728
729 fn isolate_node(&mut self, node_handle: Handle<impl ObjectOrVariant<Self::Node>>);
732
733 fn pair_iter(&self) -> impl Iterator<Item = (Handle<Self::Node>, &Self::Node)>;
735
736 fn linear_iter(&self) -> impl Iterator<Item = &Self::Node>;
739
740 fn linear_iter_mut(&mut self) -> impl Iterator<Item = &mut Self::Node>;
743
744 fn try_get<U: ObjectOrVariant<Self::Node>>(&self, handle: Handle<U>) -> Result<&U, PoolError>;
756
757 fn try_get_mut<U: ObjectOrVariant<Self::Node>>(
769 &mut self,
770 handle: Handle<U>,
771 ) -> Result<&mut U, PoolError>;
772
773 fn node(&self, handle: Handle<Self::Node>) -> &Self::Node {
775 self.try_get_node(handle).unwrap()
776 }
777
778 fn node_mut(&mut self, handle: Handle<Self::Node>) -> &mut Self::Node {
780 self.try_get_node_mut(handle).unwrap()
781 }
782
783 fn try_get_node_by_uuid(&self, uuid: Uuid) -> Option<&Self::Node> {
785 self.linear_iter().find(|n| n.instance_id() == uuid)
786 }
787
788 fn try_get_node_by_uuid_mut(&mut self, uuid: Uuid) -> Option<&mut Self::Node> {
790 self.linear_iter_mut().find(|n| n.instance_id() == uuid)
791 }
792
793 #[inline]
818 #[allow(clippy::unnecessary_to_owned)] fn change_hierarchy_root(
820 &mut self,
821 prev_root: Handle<impl ObjectOrVariant<Self::Node>>,
822 new_root: Handle<impl ObjectOrVariant<Self::Node>>,
823 ) -> LinkScheme<Self::Node> {
824 let prev_root = prev_root.to_base();
825 let new_root = new_root.to_base();
826
827 let mut scheme = LinkScheme::default();
828
829 if prev_root == new_root {
830 return scheme;
831 }
832
833 scheme
834 .links
835 .push((prev_root, self.node(prev_root).parent()));
836
837 scheme.links.push((new_root, self.node(new_root).parent()));
838
839 self.isolate_node(new_root);
840
841 for prev_root_child in self.node(prev_root).children().to_vec() {
842 self.link_nodes(prev_root_child, new_root);
843 scheme.links.push((prev_root_child, prev_root));
844 }
845
846 self.link_nodes(prev_root, new_root);
847
848 if prev_root == self.root() {
849 self.set_root(new_root);
850 scheme.root = prev_root;
851 } else {
852 scheme.root = self.root();
853 }
854
855 scheme
856 }
857
858 #[inline]
861 fn apply_link_scheme(&mut self, mut scheme: LinkScheme<Self::Node>) {
862 for (child, parent) in scheme.links.drain(..) {
863 if parent.is_some() {
864 self.link_nodes(child, parent);
865 } else {
866 self.isolate_node(child);
867 }
868 }
869 if scheme.root.is_some() {
870 self.set_root(scheme.root);
871 }
872 }
873
874 #[inline]
876 fn remove_nodes(&mut self, nodes: &[Handle<impl ObjectOrVariant<Self::Node>>]) {
877 for &node in nodes {
878 if self.is_valid_handle(node) {
879 self.remove_node(node)
880 }
881 }
882 }
883
884 #[inline]
886 fn try_get_of_type<T>(&self, handle: Handle<Self::Node>) -> Result<&T, PoolError>
887 where
888 T: 'static,
889 {
890 self.try_get_node(handle)
891 .and_then(|n| {
892 n.query_component_ref(TypeId::of::<T>())
893 .ok_or(PoolError::NoSuchComponent(handle.into()))
894 })
895 .and_then(|c| {
896 c.downcast_ref()
897 .ok_or(PoolError::InvalidType(handle.into()))
898 })
899 }
900
901 #[inline]
903 fn try_get_mut_of_type<T>(&mut self, handle: Handle<Self::Node>) -> Result<&mut T, PoolError>
904 where
905 T: 'static,
906 {
907 self.try_get_node_mut(handle)
908 .and_then(|n| {
909 n.query_component_mut(TypeId::of::<T>())
910 .ok_or(PoolError::NoSuchComponent(handle.into()))
911 })
912 .and_then(|c| {
913 c.downcast_mut()
914 .ok_or(PoolError::InvalidType(handle.into()))
915 })
916 }
917
918 #[inline]
921 fn has_component<T>(&self, handle: Handle<impl ObjectOrVariant<Self::Node>>) -> bool
922 where
923 T: 'static,
924 {
925 self.try_get_of_type::<T>(handle.to_base()).is_ok()
926 }
927
928 #[inline]
931 fn find_map<C, T>(
932 &self,
933 root_node: Handle<impl ObjectOrVariant<Self::Node>>,
934 cmp: &mut C,
935 ) -> Option<(Handle<Self::Node>, &T)>
936 where
937 C: FnMut(&Self::Node) -> Option<&T>,
938 T: ?Sized,
939 {
940 let root_node = root_node.to_base();
941 self.try_get_node(root_node).ok().and_then(|root| {
942 if let Some(x) = cmp(root) {
943 Some((root_node, x))
944 } else {
945 root.children().iter().find_map(|c| self.find_map(*c, cmp))
946 }
947 })
948 }
949
950 #[inline]
953 fn find_up<C>(
954 &self,
955 root_node: Handle<impl ObjectOrVariant<Self::Node>>,
956 cmp: &mut C,
957 ) -> Option<(Handle<Self::Node>, &Self::Node)>
958 where
959 C: FnMut(&Self::Node) -> bool,
960 {
961 let mut handle = root_node.to_base();
962 while let Ok(node) = self.try_get_node(handle) {
963 if cmp(node) {
964 return Some((handle, node));
965 }
966 handle = node.parent();
967 }
968 None
969 }
970
971 #[inline]
974 fn find_handle_up<C>(
975 &self,
976 root_node: Handle<impl ObjectOrVariant<Self::Node>>,
977 cmp: &mut C,
978 ) -> Handle<Self::Node>
979 where
980 C: FnMut(&Self::Node) -> bool,
981 {
982 self.find_up(root_node, cmp)
983 .map(|(h, _)| h)
984 .unwrap_or_default()
985 }
986
987 #[inline]
988 fn find_component_up<T>(
989 &self,
990 node_handle: Handle<impl ObjectOrVariant<Self::Node>>,
991 ) -> Option<(Handle<Self::Node>, &T)>
992 where
993 T: 'static,
994 {
995 self.find_up_map(node_handle, &mut |node| {
996 node.query_component_ref(TypeId::of::<T>())
997 })
998 .and_then(|(handle, c)| c.downcast_ref::<T>().map(|typed| (handle, typed)))
999 }
1000
1001 #[inline]
1002 fn find_component<T>(
1003 &self,
1004 node_handle: Handle<impl ObjectOrVariant<Self::Node>>,
1005 ) -> Option<(Handle<Self::Node>, &T)>
1006 where
1007 T: 'static,
1008 {
1009 self.find_map(node_handle, &mut |node| {
1010 node.query_component_ref(TypeId::of::<T>())
1011 })
1012 .and_then(|(handle, c)| c.downcast_ref::<T>().map(|typed| (handle, typed)))
1013 }
1014
1015 #[inline]
1018 fn find_up_map<C, T>(
1019 &self,
1020 root_node: Handle<impl ObjectOrVariant<Self::Node>>,
1021 cmp: &mut C,
1022 ) -> Option<(Handle<Self::Node>, &T)>
1023 where
1024 C: FnMut(&Self::Node) -> Option<&T>,
1025 T: ?Sized,
1026 {
1027 let mut handle = root_node.to_base();
1028 while let Ok(node) = self.try_get_node(handle) {
1029 if let Some(x) = cmp(node) {
1030 return Some((handle, x));
1031 }
1032 handle = node.parent();
1033 }
1034 None
1035 }
1036
1037 #[inline]
1040 fn find_by_name(
1041 &self,
1042 root_node: Handle<impl ObjectOrVariant<Self::Node>>,
1043 name: &str,
1044 ) -> Option<(Handle<Self::Node>, &Self::Node)> {
1045 self.find(root_node, &mut |node| node.name() == name)
1046 }
1047
1048 #[inline]
1051 fn find_up_by_name(
1052 &self,
1053 root_node: Handle<impl ObjectOrVariant<Self::Node>>,
1054 name: &str,
1055 ) -> Option<(Handle<Self::Node>, &Self::Node)> {
1056 self.find_up(root_node, &mut |node| node.name() == name)
1057 }
1058
1059 #[inline]
1062 fn find_by_name_from_root(&self, name: &str) -> Option<(Handle<Self::Node>, &Self::Node)> {
1063 self.find_by_name(self.root(), name)
1064 }
1065
1066 #[inline]
1067 fn find_handle_by_name_from_root(&self, name: &str) -> Handle<Self::Node> {
1068 self.find_by_name(self.root(), name)
1069 .map(|(h, _)| h)
1070 .unwrap_or_default()
1071 }
1072
1073 #[inline]
1076 fn find_from_root<C>(&self, cmp: &mut C) -> Option<(Handle<Self::Node>, &Self::Node)>
1077 where
1078 C: FnMut(&Self::Node) -> bool,
1079 {
1080 self.find(self.root(), cmp)
1081 }
1082
1083 #[inline]
1087 fn find<C>(
1088 &self,
1089 root_node: Handle<impl ObjectOrVariant<Self::Node>>,
1090 cmp: &mut C,
1091 ) -> Option<(Handle<Self::Node>, &Self::Node)>
1092 where
1093 C: FnMut(&Self::Node) -> bool,
1094 {
1095 let root_node = root_node.to_base();
1096 self.try_get_node(root_node).ok().and_then(|root| {
1097 if cmp(root) {
1098 Some((root_node, root))
1099 } else {
1100 root.children().iter().find_map(|c| self.find(*c, cmp))
1101 }
1102 })
1103 }
1104
1105 #[inline]
1108 fn find_handle<C>(
1109 &self,
1110 root_node: Handle<impl ObjectOrVariant<Self::Node>>,
1111 cmp: &mut C,
1112 ) -> Handle<Self::Node>
1113 where
1114 C: FnMut(&Self::Node) -> bool,
1115 {
1116 self.find(root_node, cmp)
1117 .map(|(h, _)| h)
1118 .unwrap_or_default()
1119 }
1120
1121 #[inline]
1134 fn relative_position(
1135 &self,
1136 child: Handle<impl ObjectOrVariant<Self::Node>>,
1137 offset: isize,
1138 ) -> Option<(Handle<Self::Node>, usize)> {
1139 let child = child.to_base();
1140 let parents_parent_handle = self.try_get_node(child).ok()?.parent();
1141 let parents_parent_ref = self.try_get_node(parents_parent_handle).ok()?;
1142 let position = parents_parent_ref.child_position(child)?;
1143 Some((
1144 parents_parent_handle,
1145 ((position as isize + offset) as usize).clamp(0, parents_parent_ref.children().len()),
1146 ))
1147 }
1148
1149 #[inline]
1151 fn traverse_iter(
1152 &self,
1153 from: Handle<impl ObjectOrVariant<Self::Node>>,
1154 ) -> impl Iterator<Item = (Handle<Self::Node>, &Self::Node)> {
1155 let from = from.to_base();
1156 self.try_get_node(from).expect("Handle must be valid!");
1157 GraphTraverseIterator {
1158 graph: self,
1159 stack: vec![from],
1160 }
1161 }
1162
1163 #[inline]
1165 fn traverse_handle_iter(
1166 &self,
1167 from: Handle<impl ObjectOrVariant<Self::Node>>,
1168 ) -> impl Iterator<Item = Handle<Self::Node>> {
1169 self.traverse_iter(from).map(|(handle, _)| handle)
1170 }
1171
1172 fn restore_integrity<F>(
1176 &mut self,
1177 mut instantiate: F,
1178 ) -> Vec<(Handle<Self::Node>, Resource<Self::Prefab>)>
1179 where
1180 F: FnMut(
1181 Resource<Self::Prefab>,
1182 &Self::Prefab,
1183 Handle<Self::Node>,
1184 &mut Self,
1185 ) -> (Handle<Self::Node>, NodeHandleMap<Self::Node>),
1186 {
1187 Log::writeln(MessageKind::Information, "Checking integrity...");
1188
1189 let instances = self
1190 .pair_iter()
1191 .filter_map(|(h, n)| {
1192 if n.is_resource_instance_root() {
1193 Some((h, n.resource().unwrap()))
1194 } else {
1195 None
1196 }
1197 })
1198 .collect::<Vec<_>>();
1199
1200 let instance_count = instances.len();
1201 let mut restored_count = 0;
1202
1203 for (instance_root, resource) in instances.iter().cloned() {
1204 let mut nodes_to_delete = Vec::new();
1206 for (_, node) in self.traverse_iter(instance_root) {
1207 if let Some(resource) = node.resource() {
1208 if let Some(model) = resource.state().data() {
1209 if !model
1210 .graph()
1211 .is_valid_handle(node.original_handle_in_resource())
1212 {
1213 nodes_to_delete.push(node.self_handle());
1214
1215 Log::warn(format!(
1216 "Node {} ({}:{}) and its children will be deleted, because it \
1217 does not exist in the parent asset!",
1218 node.name(),
1219 node.self_handle().index(),
1220 node.self_handle().generation(),
1221 ))
1222 }
1223 } else {
1224 Log::warn(format!(
1225 "Node {} ({}:{}) and its children will be deleted, because its \
1226 parent asset failed to load!",
1227 node.name(),
1228 node.self_handle().index(),
1229 node.self_handle().generation(),
1230 ))
1231 }
1232 }
1233 }
1234
1235 for node_to_delete in nodes_to_delete {
1236 if self.is_valid_handle(node_to_delete) {
1237 self.remove_node(node_to_delete);
1238 }
1239 }
1240
1241 let mut model = resource.state();
1243 let model_kind = model.kind();
1244 if let Some(data) = model.data() {
1245 let resource_graph = data.graph();
1246
1247 let Ok(resource_instance_root) = self
1248 .try_get_node(instance_root)
1249 .map(|n| n.original_handle_in_resource())
1250 else {
1251 continue;
1252 };
1253
1254 if resource_instance_root.is_none() {
1255 let instance = self.node(instance_root);
1256 Log::writeln(
1257 MessageKind::Warning,
1258 format!(
1259 "There is an instance of resource {} \
1260 but original node {} cannot be found!",
1261 model_kind,
1262 instance.name()
1263 ),
1264 );
1265
1266 continue;
1267 }
1268
1269 let mut traverse_stack = vec![resource_instance_root];
1270 while let Some(resource_node_handle) = traverse_stack.pop() {
1271 let resource_node = resource_graph.node(resource_node_handle);
1272
1273 let mut compare =
1276 |n: &Self::Node| n.original_handle_in_resource() == resource_node_handle;
1277
1278 if resource_node_handle != resource_graph.root()
1279 && self.find(instance_root, &mut compare).is_none()
1280 {
1281 Log::writeln(
1282 MessageKind::Warning,
1283 format!(
1284 "Instance of node {} is missing. Restoring integrity...",
1285 resource_node.name()
1286 ),
1287 );
1288
1289 let (copy, old_to_new_mapping) =
1291 instantiate(resource.clone(), data, resource_node_handle, self);
1292
1293 restored_count += old_to_new_mapping.inner().len();
1294
1295 if resource_node.parent().is_some() {
1297 let parent = self.find(instance_root, &mut |n| {
1298 n.original_handle_in_resource() == resource_node.parent()
1299 });
1300
1301 if let Some((parent_handle, _)) = parent {
1302 self.link_nodes(copy, parent_handle);
1303 } else {
1304 self.link_nodes(copy, instance_root);
1306 }
1307 } else {
1308 self.link_nodes(copy, instance_root);
1310 }
1311 }
1312
1313 traverse_stack.extend_from_slice(resource_node.children());
1314 }
1315 }
1316 }
1317
1318 Log::writeln(
1319 MessageKind::Information,
1320 format!(
1321 "Integrity restored for {instance_count} instances! {restored_count} new nodes were added!"
1322 ),
1323 );
1324
1325 instances
1326 }
1327
1328 fn restore_original_handles_and_inherit_properties<F>(
1332 &mut self,
1333 ignored_types: &[TypeId],
1334 mut before_inherit: F,
1335 ) where
1336 F: FnMut(&Self::Node, &mut Self::Node),
1337 {
1338 let mut ignored_types = ignored_types.to_vec();
1339 ignored_types.push(TypeId::of::<UntypedResource>());
1341
1342 for node in self.linear_iter_mut() {
1346 if let Some(model) = node.resource() {
1347 let mut header = model.state();
1348 let model_kind = header.kind();
1349 if let Some(data) = header.data() {
1350 let resource_graph = data.graph();
1351
1352 let resource_node = match data.mapping() {
1353 NodeMapping::UseNames => {
1354 resource_graph
1359 .pair_iter()
1360 .find_map(|(handle, resource_node)| {
1361 if resource_node.name() == node.name() {
1362 Some((resource_node, handle))
1363 } else {
1364 None
1365 }
1366 })
1367 }
1368 NodeMapping::UseHandles => {
1369 resource_graph
1371 .try_get_node(node.original_handle_in_resource())
1372 .map(|resource_node| {
1373 (resource_node, node.original_handle_in_resource())
1374 })
1375 .ok()
1376 }
1377 };
1378
1379 if let Some((resource_node, original)) = resource_node {
1380 node.set_original_handle_in_resource(original);
1381
1382 before_inherit(resource_node, node);
1383
1384 let mut types_match = true;
1387 node.as_reflect(&mut |node_reflect| {
1388 resource_node.as_reflect(&mut |resource_node_reflect| {
1389 types_match =
1390 node_reflect.type_id() == resource_node_reflect.type_id();
1391
1392 if !types_match {
1393 Log::warn(format!(
1394 "Node {}({}:{}) instance \
1395 have different type than in the respective parent \
1396 asset {}. The type will be fixed.",
1397 node.name(),
1398 node.self_handle().index(),
1399 node.self_handle().generation(),
1400 model_kind
1401 ));
1402 }
1403 })
1404 });
1405 if !types_match {
1406 let base = node.base().clone();
1407 let mut resource_node_clone = resource_node.clone();
1408 variable::mark_inheritable_properties_non_modified(
1409 &mut resource_node_clone as &mut dyn Reflect,
1410 &ignored_types,
1411 );
1412 resource_node_clone.set_base(base);
1413 *node = resource_node_clone;
1414 }
1415
1416 node.as_reflect_mut(&mut |node_reflect| {
1418 resource_node.as_reflect(&mut |resource_node_reflect| {
1419 Log::verify(variable::try_inherit_properties(
1420 node_reflect,
1421 resource_node_reflect,
1422 &ignored_types,
1423 ));
1424 })
1425 })
1426 } else {
1427 Log::warn(format!(
1428 "Unable to find original handle for node {}. The node will be removed!",
1429 node.name(),
1430 ))
1431 }
1432 }
1433 }
1434 }
1435
1436 Log::writeln(MessageKind::Information, "Original handles resolved!");
1437 }
1438
1439 fn remap_handles(&mut self, instances: &[(Handle<Self::Node>, Resource<Self::Prefab>)]) {
1446 for (instance_root, resource) in instances {
1447 let mut old_new_mapping = NodeHandleMap::default();
1450 let mut traverse_stack = vec![*instance_root];
1451 while let Some(node_handle) = traverse_stack.pop() {
1452 let Ok(node) = self.try_get_node(node_handle) else {
1453 continue;
1454 };
1455 if let Some(node_resource) = node.resource().as_ref() {
1456 if node_resource == resource {
1458 let previous_mapping =
1459 old_new_mapping.insert(node.original_handle_in_resource(), node_handle);
1460 if previous_mapping.is_some() {
1462 Log::warn(format!(
1463 "There are multiple original nodes for {:?}! Previous was {:?}. \
1464 This can happen if a respective node was deleted.",
1465 node_handle,
1466 node.original_handle_in_resource()
1467 ))
1468 }
1469 }
1470 }
1471
1472 traverse_stack.extend_from_slice(node.children());
1473 }
1474
1475 for (_, handle) in old_new_mapping.inner().iter() {
1478 old_new_mapping.remap_inheritable_handles(
1479 self.node_mut(*handle),
1480 &[TypeId::of::<UntypedResource>()],
1481 );
1482 }
1483 }
1484 }
1485}
1486
1487pub struct GraphTraverseIterator<'a, G: ?Sized, N> {
1489 graph: &'a G,
1490 stack: Vec<Handle<N>>,
1491}
1492
1493impl<'a, G: ?Sized, N> Iterator for GraphTraverseIterator<'a, G, N>
1494where
1495 G: SceneGraph<Node = N>,
1496 N: SceneGraphNode,
1497{
1498 type Item = (Handle<N>, &'a N);
1499
1500 #[inline]
1501 fn next(&mut self) -> Option<Self::Item> {
1502 if let Some(handle) = self.stack.pop() {
1503 let node = self.graph.node(handle);
1504
1505 for child_handle in node.children() {
1506 self.stack.push(*child_handle);
1507 }
1508
1509 return Some((handle, node));
1510 }
1511
1512 None
1513 }
1514}
1515
1516#[cfg(test)]
1517mod test {
1518 use crate::{NodeHandleMap, NodeMapping, PrefabData, SceneGraph, SceneGraphNode};
1519 use fyrox_core::pool::{ObjectOrVariant, ObjectOrVariantHelper, PoolError};
1520 use fyrox_core::{
1521 define_as_any_trait,
1522 pool::{Handle, PayloadContainer, Pool},
1523 reflect::prelude::*,
1524 type_traits::prelude::*,
1525 visitor::prelude::*,
1526 NameProvider,
1527 };
1528 use fyrox_resource::{untyped::UntypedResource, Resource, ResourceData};
1529 use std::marker::PhantomData;
1530 use std::{
1531 any::{Any, TypeId},
1532 error::Error,
1533 fmt::Debug,
1534 ops::{Deref, DerefMut, Index, IndexMut},
1535 path::Path,
1536 };
1537
1538 #[derive(Visit, Reflect, Debug, Clone)]
1539 pub struct Base {
1540 name: String,
1541 self_handle: Handle<Node>,
1542 is_resource_instance_root: bool,
1543 original_handle_in_resource: Handle<Node>,
1544 resource: Option<Resource<Graph>>,
1545 parent: Handle<Node>,
1546 children: Vec<Handle<Node>>,
1547 instance_id: Uuid,
1548 }
1549
1550 impl Default for Base {
1551 fn default() -> Self {
1552 Self {
1553 name: Default::default(),
1554 self_handle: Default::default(),
1555 is_resource_instance_root: Default::default(),
1556 original_handle_in_resource: Default::default(),
1557 resource: Default::default(),
1558 parent: Default::default(),
1559 children: Default::default(),
1560 instance_id: Uuid::new_v4(),
1561 }
1562 }
1563 }
1564
1565 pub trait BaseNodeTrait: Any + Debug + Deref<Target = Base> + DerefMut + Send {
1567 fn clone_box(&self) -> Node;
1571 }
1572
1573 impl<T> BaseNodeTrait for T
1574 where
1575 T: Clone + NodeTrait + 'static,
1576 {
1577 fn clone_box(&self) -> Node {
1578 Node(Box::new(self.clone()))
1579 }
1580 }
1581
1582 define_as_any_trait!(NodeAsAny => NodeTrait);
1583
1584 pub trait NodeTrait: BaseNodeTrait + Reflect + Visit + ComponentProvider + NodeAsAny {}
1585
1586 impl<T: NodeTrait> ObjectOrVariantHelper<Node, T> for PhantomData<T> {
1589 fn convert_to_dest_type_helper(node: &Node) -> Option<&T> {
1590 NodeAsAny::as_any(node.0.deref()).downcast_ref()
1591 }
1592 fn convert_to_dest_type_helper_mut(node: &mut Node) -> Option<&mut T> {
1593 NodeAsAny::as_any_mut(node.0.deref_mut()).downcast_mut()
1594 }
1595 }
1596
1597 #[derive(ComponentProvider, Debug)]
1598 pub struct Node(Box<dyn NodeTrait>);
1599
1600 impl Clone for Node {
1601 fn clone(&self) -> Self {
1602 self.0.clone_box()
1603 }
1604 }
1605
1606 impl Node {
1607 fn new(node: impl NodeTrait) -> Self {
1608 Self(Box::new(node))
1609 }
1610 }
1611
1612 impl Visit for Node {
1613 fn visit(&mut self, name: &str, visitor: &mut Visitor) -> VisitResult {
1614 self.0.visit(name, visitor)
1615 }
1616 }
1617
1618 impl Reflect for Node {
1619 fn source_path() -> &'static str {
1620 file!()
1621 }
1622
1623 fn type_name(&self) -> &'static str {
1624 self.0.deref().type_name()
1625 }
1626
1627 fn doc(&self) -> &'static str {
1628 self.0.deref().doc()
1629 }
1630
1631 fn assembly_name(&self) -> &'static str {
1632 self.0.deref().assembly_name()
1633 }
1634
1635 fn type_assembly_name() -> &'static str {
1636 env!("CARGO_PKG_NAME")
1637 }
1638
1639 fn fields_ref(&self, func: &mut dyn FnMut(&[FieldRef])) {
1640 self.0.deref().fields_ref(func)
1641 }
1642
1643 fn fields_mut(&mut self, func: &mut dyn FnMut(&mut [FieldMut])) {
1644 self.0.deref_mut().fields_mut(func)
1645 }
1646
1647 fn into_any(self: Box<Self>) -> Box<dyn Any> {
1648 Reflect::into_any(self.0)
1649 }
1650
1651 fn as_any(&self, func: &mut dyn FnMut(&dyn Any)) {
1652 Reflect::as_any(self.0.deref(), func)
1653 }
1654
1655 fn as_any_mut(&mut self, func: &mut dyn FnMut(&mut dyn Any)) {
1656 Reflect::as_any_mut(self.0.deref_mut(), func)
1657 }
1658
1659 fn as_reflect(&self, func: &mut dyn FnMut(&dyn Reflect)) {
1660 self.0.deref().as_reflect(func)
1661 }
1662
1663 fn as_reflect_mut(&mut self, func: &mut dyn FnMut(&mut dyn Reflect)) {
1664 self.0.deref_mut().as_reflect_mut(func)
1665 }
1666
1667 fn set(&mut self, value: Box<dyn Reflect>) -> Result<Box<dyn Reflect>, Box<dyn Reflect>> {
1668 self.0.deref_mut().set(value)
1669 }
1670
1671 fn set_field(
1672 &mut self,
1673 field: &str,
1674 value: Box<dyn Reflect>,
1675 func: &mut dyn FnMut(Result<Box<dyn Reflect>, SetFieldError>),
1676 ) {
1677 self.0.deref_mut().set_field(field, value, func)
1678 }
1679
1680 fn field(&self, name: &str, func: &mut dyn FnMut(Option<&dyn Reflect>)) {
1681 self.0.deref().field(name, func)
1682 }
1683
1684 fn field_mut(&mut self, name: &str, func: &mut dyn FnMut(Option<&mut dyn Reflect>)) {
1685 self.0.deref_mut().field_mut(name, func)
1686 }
1687
1688 fn derived_types() -> &'static [TypeId] {
1689 &[]
1690 }
1691
1692 fn query_derived_types(&self) -> &'static [TypeId] {
1693 Self::derived_types()
1694 }
1695
1696 fn try_clone_box(&self) -> Option<Box<dyn Reflect>> {
1697 Some(Box::new(self.clone()))
1698 }
1699 }
1700
1701 impl NameProvider for Node {
1702 fn name(&self) -> &str {
1703 &self.name
1704 }
1705 }
1706
1707 impl Deref for Node {
1708 type Target = Base;
1709
1710 fn deref(&self) -> &Self::Target {
1711 self.0.deref()
1712 }
1713 }
1714
1715 impl DerefMut for Node {
1716 fn deref_mut(&mut self) -> &mut Self::Target {
1717 self.0.deref_mut()
1718 }
1719 }
1720
1721 #[derive(Debug, Default, Clone, Reflect)]
1724 pub struct NodeContainer(Option<Node>);
1725
1726 impl Visit for NodeContainer {
1727 fn visit(&mut self, _name: &str, _visitor: &mut Visitor) -> VisitResult {
1728 Ok(())
1730 }
1731 }
1732
1733 impl PayloadContainer for NodeContainer {
1734 type Element = Node;
1735
1736 fn new_empty() -> Self {
1737 Self(None)
1738 }
1739
1740 fn new(element: Self::Element) -> Self {
1741 Self(Some(element))
1742 }
1743
1744 fn is_some(&self) -> bool {
1745 self.0.is_some()
1746 }
1747
1748 fn as_ref(&self) -> Option<&Self::Element> {
1749 self.0.as_ref()
1750 }
1751
1752 fn as_mut(&mut self) -> Option<&mut Self::Element> {
1753 self.0.as_mut()
1754 }
1755
1756 fn replace(&mut self, element: Self::Element) -> Option<Self::Element> {
1757 self.0.replace(element)
1758 }
1759
1760 fn take(&mut self) -> Option<Self::Element> {
1761 self.0.take()
1762 }
1763 }
1764
1765 impl SceneGraphNode for Node {
1766 type Base = Base;
1767 type SceneGraph = Graph;
1768 type ResourceData = Graph;
1769
1770 #[allow(clippy::explicit_auto_deref)] fn base(&self) -> &Self::Base {
1772 &**self
1773 }
1774
1775 fn set_base(&mut self, base: Self::Base) {
1776 **self = base;
1777 }
1778
1779 fn is_resource_instance_root(&self) -> bool {
1780 self.is_resource_instance_root
1781 }
1782
1783 fn original_handle_in_resource(&self) -> Handle<Self> {
1784 self.original_handle_in_resource
1785 }
1786
1787 fn set_original_handle_in_resource(&mut self, handle: Handle<Self>) {
1788 self.original_handle_in_resource = handle;
1789 }
1790
1791 fn resource(&self) -> Option<Resource<Self::ResourceData>> {
1792 self.resource.clone()
1793 }
1794
1795 fn self_handle(&self) -> Handle<Self> {
1796 self.self_handle
1797 }
1798
1799 fn parent(&self) -> Handle<Self> {
1800 self.parent
1801 }
1802
1803 fn children(&self) -> &[Handle<Self>] {
1804 &self.children
1805 }
1806
1807 fn children_mut(&mut self) -> &mut [Handle<Self>] {
1808 &mut self.children
1809 }
1810
1811 fn instance_id(&self) -> Uuid {
1812 self.instance_id
1813 }
1814 }
1815
1816 #[derive(Default, Clone, TypeUuidProvider, Visit, Reflect, Debug)]
1817 #[type_uuid(id = "fc887063-7780-44af-8710-5e0bcf9a83fd")]
1818 pub struct Graph {
1819 root: Handle<Node>,
1820 nodes: Pool<Node, NodeContainer>,
1821 }
1822
1823 impl ResourceData for Graph {
1824 fn type_uuid(&self) -> Uuid {
1825 <Graph as TypeUuidProvider>::type_uuid()
1826 }
1827
1828 fn save(&mut self, _path: &Path) -> Result<(), Box<dyn Error>> {
1829 Ok(())
1830 }
1831
1832 fn can_be_saved(&self) -> bool {
1833 false
1834 }
1835
1836 fn try_clone_box(&self) -> Option<Box<dyn ResourceData>> {
1837 Some(Box::new(self.clone()))
1838 }
1839 }
1840
1841 impl PrefabData for Graph {
1842 type Graph = Graph;
1843
1844 fn graph(&self) -> &Self::Graph {
1845 self
1846 }
1847
1848 fn mapping(&self) -> NodeMapping {
1849 NodeMapping::UseHandles
1850 }
1851 }
1852
1853 impl Index<Handle<Node>> for Graph {
1854 type Output = Node;
1855
1856 #[inline]
1857 fn index(&self, index: Handle<Node>) -> &Self::Output {
1858 &self.nodes[index]
1859 }
1860 }
1861
1862 impl IndexMut<Handle<Node>> for Graph {
1863 #[inline]
1864 fn index_mut(&mut self, index: Handle<Node>) -> &mut Self::Output {
1865 &mut self.nodes[index]
1866 }
1867 }
1868
1869 impl SceneGraph for Graph {
1870 type Prefab = Graph;
1871 type NodeContainer = NodeContainer;
1872 type Node = Node;
1873
1874 fn summary(&self) -> String {
1875 "Summary".to_string()
1876 }
1877
1878 fn root(&self) -> Handle<Self::Node> {
1879 self.root
1880 }
1881
1882 fn set_root(&mut self, root: Handle<Self::Node>) {
1883 self.root = root;
1884 }
1885
1886 fn is_valid_handle(&self, handle: Handle<impl ObjectOrVariant<Self::Node>>) -> bool {
1887 self.nodes.is_valid_handle(handle)
1888 }
1889
1890 fn add_node(&mut self, node: Self::Node) -> Handle<Self::Node> {
1891 let handle = self.nodes.next_free_handle();
1892 self.add_node_at_handle(node, handle);
1893 handle
1894 }
1895
1896 fn add_node_at_handle(&mut self, mut node: Self::Node, handle: Handle<Self::Node>) {
1897 let children = node.children.clone();
1898 node.children.clear();
1899 let handle = self
1900 .nodes
1901 .spawn_at_handle(handle, node)
1902 .expect("The handle must be valid");
1903
1904 if self.root.is_none() {
1905 self.root = handle;
1906 } else {
1907 self.link_nodes(handle, self.root);
1908 }
1909
1910 for child in children {
1911 self.link_nodes(child, handle);
1912 }
1913
1914 let node = &mut self.nodes[handle];
1915 node.self_handle = handle;
1916 }
1917
1918 fn remove_node(&mut self, node_handle: Handle<impl ObjectOrVariant<Self::Node>>) {
1919 let node_handle = node_handle.to_base();
1920 self.isolate_node(node_handle);
1921 let mut stack = vec![node_handle];
1922 while let Some(handle) = stack.pop() {
1923 stack.extend_from_slice(self.nodes[handle].children());
1924 self.nodes.free(handle);
1925 }
1926 }
1927
1928 fn link_nodes(
1929 &mut self,
1930 child: Handle<impl ObjectOrVariant<Self::Node>>,
1931 parent: Handle<impl ObjectOrVariant<Self::Node>>,
1932 ) {
1933 let child = child.to_base();
1934 let parent = parent.to_base();
1935 self.isolate_node(child);
1936 self.nodes[child].parent = parent;
1937 self.nodes[parent].children.push(child);
1938 }
1939
1940 fn unlink_node(&mut self, node_handle: Handle<impl ObjectOrVariant<Self::Node>>) {
1941 self.isolate_node(node_handle);
1942 self.link_nodes(node_handle, self.root);
1943 }
1944
1945 fn isolate_node(&mut self, node_handle: Handle<impl ObjectOrVariant<Self::Node>>) {
1946 let node_handle = node_handle.to_base();
1947
1948 let parent_handle =
1949 std::mem::replace(&mut self.nodes[node_handle].parent, Handle::NONE);
1950
1951 if let Ok(parent) = self.nodes.try_borrow_mut(parent_handle) {
1952 if let Some(i) = parent.children().iter().position(|h| *h == node_handle) {
1953 parent.children.remove(i);
1954 }
1955 }
1956 }
1957
1958 fn try_get_node(&self, handle: Handle<Self::Node>) -> Result<&Self::Node, PoolError> {
1959 self.nodes.try_borrow(handle)
1960 }
1961
1962 fn try_get_node_mut(
1963 &mut self,
1964 handle: Handle<Self::Node>,
1965 ) -> Result<&mut Self::Node, PoolError> {
1966 self.nodes.try_borrow_mut(handle)
1967 }
1968
1969 fn actual_type_id(&self, handle: Handle<Self::Node>) -> Result<TypeId, PoolError> {
1970 self.nodes
1971 .try_borrow(handle)
1972 .map(|n| NodeAsAny::as_any(n.0.deref()).type_id())
1973 }
1974
1975 fn derived_type_ids(&self, handle: Handle<Self::Node>) -> Result<Vec<TypeId>, PoolError> {
1976 self.nodes
1977 .try_borrow(handle)
1978 .map(|n| n.0.deref().query_derived_types().to_vec())
1979 }
1980
1981 fn actual_type_name(&self, handle: Handle<Self::Node>) -> Result<&'static str, PoolError> {
1982 self.nodes
1983 .try_borrow(handle)
1984 .map(|n| n.0.deref().type_name())
1985 }
1986
1987 fn pair_iter(&self) -> impl Iterator<Item = (Handle<Self::Node>, &Self::Node)> {
1988 self.nodes.pair_iter()
1989 }
1990
1991 fn linear_iter(&self) -> impl Iterator<Item = &Self::Node> {
1992 self.nodes.iter()
1993 }
1994
1995 fn linear_iter_mut(&mut self) -> impl Iterator<Item = &mut Self::Node> {
1996 self.nodes.iter_mut()
1997 }
1998
1999 fn try_get<U: ObjectOrVariant<Node>>(&self, handle: Handle<U>) -> Result<&U, PoolError> {
2000 self.nodes.try_get(handle)
2001 }
2002
2003 fn try_get_mut<U: ObjectOrVariant<Node>>(
2004 &mut self,
2005 handle: Handle<U>,
2006 ) -> Result<&mut U, PoolError> {
2007 self.nodes.try_get_mut(handle)
2008 }
2009 }
2010
2011 fn remap_handles(old_new_mapping: &NodeHandleMap<Node>, dest_graph: &mut Graph) {
2012 for (_, &new_node_handle) in old_new_mapping.inner().iter() {
2014 old_new_mapping.remap_handles(
2015 &mut dest_graph.nodes[new_node_handle],
2016 &[TypeId::of::<UntypedResource>()],
2017 );
2018 }
2019 }
2020
2021 fn clear_links(mut node: Node) -> Node {
2022 node.children.clear();
2023 node.parent = Handle::NONE;
2024 node
2025 }
2026
2027 impl Graph {
2028 #[inline]
2029 pub fn copy_node(
2030 &self,
2031 node_handle: Handle<Node>,
2032 dest_graph: &mut Graph,
2033 ) -> (Handle<Node>, NodeHandleMap<Node>) {
2034 let mut old_new_mapping = NodeHandleMap::default();
2035 let root_handle = self.copy_node_raw(node_handle, dest_graph, &mut old_new_mapping);
2036
2037 remap_handles(&old_new_mapping, dest_graph);
2038
2039 (root_handle, old_new_mapping)
2040 }
2041 fn copy_node_raw(
2042 &self,
2043 root_handle: Handle<Node>,
2044 dest_graph: &mut Graph,
2045 old_new_mapping: &mut NodeHandleMap<Node>,
2046 ) -> Handle<Node> {
2047 let src_node = &self.nodes[root_handle];
2048 let dest_node = clear_links(src_node.clone());
2049 let dest_copy_handle = dest_graph.add_node(dest_node);
2050 old_new_mapping.insert(root_handle, dest_copy_handle);
2051 for &src_child_handle in src_node.children() {
2052 let dest_child_handle =
2053 self.copy_node_raw(src_child_handle, dest_graph, old_new_mapping);
2054 if !dest_child_handle.is_none() {
2055 dest_graph.link_nodes(dest_child_handle, dest_copy_handle);
2056 }
2057 }
2058 dest_copy_handle
2059 }
2060 }
2061
2062 #[derive(Clone, Reflect, Visit, Default, Debug, ComponentProvider)]
2063 #[reflect(derived_type = "Node")]
2064 pub struct Pivot {
2065 base: Base,
2066 }
2067
2068 impl NodeTrait for Pivot {}
2069
2070 impl Deref for Pivot {
2071 type Target = Base;
2072
2073 fn deref(&self) -> &Self::Target {
2074 &self.base
2075 }
2076 }
2077
2078 impl DerefMut for Pivot {
2079 fn deref_mut(&mut self) -> &mut Self::Target {
2080 &mut self.base
2081 }
2082 }
2083
2084 #[derive(Clone, Reflect, Visit, Default, Debug, ComponentProvider)]
2085 #[reflect(derived_type = "Node")]
2086 pub struct RigidBody {
2087 base: Base,
2088 }
2089
2090 impl NodeTrait for RigidBody {}
2091
2092 impl Deref for RigidBody {
2093 type Target = Base;
2094
2095 fn deref(&self) -> &Self::Target {
2096 &self.base
2097 }
2098 }
2099
2100 impl DerefMut for RigidBody {
2101 fn deref_mut(&mut self) -> &mut Self::Target {
2102 &mut self.base
2103 }
2104 }
2105
2106 #[derive(Clone, Reflect, Visit, Default, Debug, ComponentProvider)]
2107 #[reflect(derived_type = "Node")]
2108 pub struct Joint {
2109 base: Base,
2110 connected_body1: Handle<RigidBody>,
2111 connected_body2: Handle<RigidBody>,
2112 }
2113
2114 impl NodeTrait for Joint {}
2115
2116 impl Deref for Joint {
2117 type Target = Base;
2118
2119 fn deref(&self) -> &Self::Target {
2120 &self.base
2121 }
2122 }
2123
2124 impl DerefMut for Joint {
2125 fn deref_mut(&mut self) -> &mut Self::Target {
2126 &mut self.base
2127 }
2128 }
2129
2130 #[test]
2131 fn test_set_child_position() {
2132 let mut graph = Graph::default();
2133
2134 let root = graph.add_node(Node::new(Pivot::default()));
2135 let a = graph.add_node(Node::new(Pivot::default()));
2136 let b = graph.add_node(Node::new(Pivot::default()));
2137 let c = graph.add_node(Node::new(Pivot::default()));
2138 let d = graph.add_node(Node::new(Pivot::default()));
2139 graph.link_nodes(a, root);
2140 graph.link_nodes(b, root);
2141 graph.link_nodes(c, root);
2142 graph.link_nodes(d, root);
2143
2144 let root_ref = &mut graph[root];
2145 assert_eq!(root_ref.set_child_position(a, 0), Some(0));
2146 assert_eq!(root_ref.set_child_position(b, 1), Some(1));
2147 assert_eq!(root_ref.set_child_position(c, 2), Some(2));
2148 assert_eq!(root_ref.set_child_position(d, 3), Some(3));
2149 assert_eq!(root_ref.children[0], a);
2150 assert_eq!(root_ref.children[1], b);
2151 assert_eq!(root_ref.children[2], c);
2152 assert_eq!(root_ref.children[3], d);
2153
2154 let initial_pos = root_ref.set_child_position(a, 3);
2155 assert_eq!(initial_pos, Some(0));
2156 assert_eq!(root_ref.children[0], b);
2157 assert_eq!(root_ref.children[1], c);
2158 assert_eq!(root_ref.children[2], d);
2159 assert_eq!(root_ref.children[3], a);
2160
2161 let prev_pos = root_ref.set_child_position(a, initial_pos.unwrap());
2162 assert_eq!(prev_pos, Some(3));
2163 assert_eq!(root_ref.children[0], a);
2164 assert_eq!(root_ref.children[1], b);
2165 assert_eq!(root_ref.children[2], c);
2166 assert_eq!(root_ref.children[3], d);
2167
2168 assert_eq!(root_ref.set_child_position(d, 1), Some(3));
2169 assert_eq!(root_ref.children[0], a);
2170 assert_eq!(root_ref.children[1], d);
2171 assert_eq!(root_ref.children[2], b);
2172 assert_eq!(root_ref.children[3], c);
2173
2174 assert_eq!(root_ref.set_child_position(d, 0), Some(1));
2175 assert_eq!(root_ref.children[0], d);
2176 assert_eq!(root_ref.children[1], a);
2177 assert_eq!(root_ref.children[2], b);
2178 assert_eq!(root_ref.children[3], c);
2179 }
2180
2181 #[test]
2182 fn test_derived_handles_mapping() {
2183 let mut prefab_graph = Graph::default();
2184
2185 prefab_graph.add_node(Node::new(Pivot::default()));
2186 let rigid_body = prefab_graph.add_node(Node::new(RigidBody::default()));
2187 let rigid_body2 = prefab_graph.add_node(Node::new(RigidBody::default()));
2188 let joint = prefab_graph.add_node(Node::new(Joint {
2189 base: Base::default(),
2190 connected_body1: rigid_body.transmute(),
2191 connected_body2: rigid_body2.transmute(),
2192 }));
2193
2194 let mut scene_graph = Graph::default();
2195 let root = scene_graph.add_node(Node::new(Pivot::default()));
2196
2197 let (_, mapping) = prefab_graph.copy_node(root, &mut scene_graph);
2198 let rigid_body_copy = mapping
2199 .inner()
2200 .get(&rigid_body)
2201 .cloned()
2202 .unwrap()
2203 .transmute::<RigidBody>();
2204 let rigid_body2_copy = mapping
2205 .inner()
2206 .get(&rigid_body2)
2207 .cloned()
2208 .unwrap()
2209 .transmute::<RigidBody>();
2210 let joint_copy = mapping.inner().get(&joint).cloned().unwrap();
2211 Reflect::as_any(&scene_graph.nodes[joint_copy], &mut |any| {
2212 let joint_copy_ref = any.downcast_ref::<Joint>().unwrap();
2213 assert_eq!(joint_copy_ref.connected_body1, rigid_body_copy);
2214 assert_eq!(joint_copy_ref.connected_body2, rigid_body2_copy);
2215 });
2216 }
2217
2218 #[test]
2219 fn test_change_root() {
2220 let mut graph = Graph::default();
2221
2222 let root = graph.add_node(Node::new(Pivot::default()));
2228 let d = graph.add_node(Node::new(Pivot::default()));
2229 let c = graph.add_node(Node::new(Pivot {
2230 base: Base {
2231 children: vec![d],
2232 ..Default::default()
2233 },
2234 }));
2235 let b = graph.add_node(Node::new(Pivot::default()));
2236 let a = graph.add_node(Node::new(Pivot {
2237 base: Base {
2238 children: vec![b, c],
2239 ..Default::default()
2240 },
2241 }));
2242 graph.link_nodes(a, root);
2243
2244 dbg!(root, a, b, c, d);
2245
2246 let link_scheme = graph.change_hierarchy_root(root, c);
2247
2248 assert_eq!(graph.root, c);
2254
2255 assert_eq!(graph[graph.root].parent, Handle::<Node>::NONE);
2256 assert_eq!(graph[graph.root].children.len(), 3);
2257
2258 assert_eq!(graph[graph.root].children[0], d);
2259 assert_eq!(graph[d].parent, graph.root);
2260 assert!(graph[d].children.is_empty());
2261
2262 assert_eq!(graph[graph.root].children[1], a);
2263 assert_eq!(graph[a].parent, graph.root);
2264
2265 assert_eq!(graph[graph.root].children[2], root);
2266 assert_eq!(graph[root].parent, graph.root);
2267
2268 assert_eq!(graph[a].children.len(), 1);
2269 assert_eq!(graph[a].children[0], b);
2270 assert_eq!(graph[b].parent, a);
2271
2272 assert!(graph[b].children.is_empty());
2273
2274 graph.apply_link_scheme(link_scheme);
2276
2277 assert_eq!(graph.root, root);
2278 assert_eq!(graph[graph.root].parent, Handle::<Node>::NONE);
2279 assert_eq!(graph[graph.root].children, vec![a]);
2280
2281 assert_eq!(graph[a].parent, root);
2282 assert_eq!(graph[a].children, vec![b, c]);
2283
2284 assert_eq!(graph[b].parent, a);
2285 assert_eq!(graph[b].children, Vec::<Handle<Node>>::new());
2286
2287 assert_eq!(graph[c].parent, a);
2288 assert_eq!(graph[c].children, vec![d]);
2289 }
2290}