fyrox_graph/
lib.rs

1// Copyright (c) 2019-present Dmitry Stepanov and Fyrox Engine contributors.
2//
3// Permission is hereby granted, free of charge, to any person obtaining a copy
4// of this software and associated documentation files (the "Software"), to deal
5// in the Software without restriction, including without limitation the rights
6// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7// copies of the Software, and to permit persons to whom the Software is
8// furnished to do so, subject to the following conditions:
9//
10// The above copyright notice and this permission notice shall be included in all
11// copies or substantial portions of the Software.
12//
13// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19// SOFTWARE.
20
21#![allow(clippy::type_complexity)]
22
23//! Graph utilities and common algorithms.
24
25pub mod constructor;
26
27use fxhash::FxHashMap;
28use fyrox_core::pool::ErasedHandle;
29use fyrox_core::{
30    log::{Log, MessageKind},
31    pool::Handle,
32    reflect::prelude::*,
33    variable::{self, InheritableVariable},
34    ComponentProvider, NameProvider,
35};
36use fyrox_resource::{untyped::UntypedResource, Resource, TypedResourceData};
37use std::any::Any;
38use std::cmp::Ordering;
39use std::fmt::Debug;
40use std::{
41    any::TypeId,
42    ops::{Deref, DerefMut},
43};
44
45#[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, Reflect)]
46#[repr(u32)]
47pub enum NodeMapping {
48    UseNames = 0,
49    UseHandles = 1,
50}
51
52/// A `OriginalHandle -> CopyHandle` map. It is used to map handles to nodes after copying.
53///
54/// For example, scene nodes have lots of cross references, the simplest cross reference is a handle
55/// to parent node, and a set of handles to children nodes. Skinned meshes also store handles to
56/// scenes nodes that serve as bones. When you copy a node, you need handles of the copy to point
57/// to respective copies. This map allows you to do this.
58///
59/// Mapping could fail if you do a partial copy of some hierarchy that does not have respective
60/// copies of nodes that must be remapped. For example you can copy just a skinned mesh, but not
61/// its bones - in this case mapping will fail, but you still can use old handles even it does not
62/// make any sense.
63pub struct NodeHandleMap<N> {
64    pub(crate) map: FxHashMap<Handle<N>, Handle<N>>,
65}
66
67impl<N> Default for NodeHandleMap<N> {
68    fn default() -> Self {
69        Self {
70            map: Default::default(),
71        }
72    }
73}
74
75impl<N> Clone for NodeHandleMap<N> {
76    fn clone(&self) -> Self {
77        Self {
78            map: self.map.clone(),
79        }
80    }
81}
82
83impl<N> NodeHandleMap<N>
84where
85    N: Reflect + NameProvider,
86{
87    /// Adds new `original -> copy` handle mapping.
88    #[inline]
89    pub fn insert(
90        &mut self,
91        original_handle: Handle<N>,
92        copy_handle: Handle<N>,
93    ) -> Option<Handle<N>> {
94        self.map.insert(original_handle, copy_handle)
95    }
96
97    /// Maps a handle to a handle of its origin, or sets it to [Handle::NONE] if there is no such node.
98    /// It should be used when you are sure that respective origin exists.
99    #[inline]
100    pub fn map(&self, handle: &mut Handle<N>) -> &Self {
101        *handle = self.map.get(handle).cloned().unwrap_or_default();
102        self
103    }
104
105    /// Maps each handle in the slice to a handle of its origin, or sets it to [Handle::NONE] if there is no such node.
106    /// It should be used when you are sure that respective origin exists.
107    #[inline]
108    pub fn map_slice<T>(&self, handles: &mut [T]) -> &Self
109    where
110        T: Deref<Target = Handle<N>> + DerefMut,
111    {
112        for handle in handles {
113            self.map(handle);
114        }
115        self
116    }
117
118    /// Tries to map a handle to a handle of its origin. If it exists, the method returns true or false otherwise.
119    /// It should be used when you not sure that respective origin exists.
120    #[inline]
121    pub fn try_map(&self, handle: &mut Handle<N>) -> bool {
122        if let Some(new_handle) = self.map.get(handle) {
123            *handle = *new_handle;
124            true
125        } else {
126            false
127        }
128    }
129
130    /// Tries to map each handle in the slice to a handle of its origin. If it exists, the method returns true or false otherwise.
131    /// It should be used when you not sure that respective origin exists.
132    #[inline]
133    pub fn try_map_slice<T>(&self, handles: &mut [T]) -> bool
134    where
135        T: Deref<Target = Handle<N>> + DerefMut,
136    {
137        let mut success = true;
138        for handle in handles {
139            success &= self.try_map(handle);
140        }
141        success
142    }
143
144    /// Tries to silently map (without setting `modified` flag) a templated handle to a handle of its origin.
145    /// If it exists, the method returns true or false otherwise. It should be used when you not sure that respective
146    /// origin exists.
147    #[inline]
148    pub fn try_map_silent(&self, inheritable_handle: &mut InheritableVariable<Handle<N>>) -> bool {
149        if let Some(new_handle) = self.map.get(inheritable_handle) {
150            inheritable_handle.set_value_silent(*new_handle);
151            true
152        } else {
153            false
154        }
155    }
156
157    /// Returns a shared reference to inner map.
158    #[inline]
159    pub fn inner(&self) -> &FxHashMap<Handle<N>, Handle<N>> {
160        &self.map
161    }
162
163    /// Returns inner map.
164    #[inline]
165    pub fn into_inner(self) -> FxHashMap<Handle<N>, Handle<N>> {
166        self.map
167    }
168
169    /// Tries to remap handles to nodes in a given entity using reflection. It finds all supported fields recursively
170    /// (`Handle<Node>`, `Vec<Handle<Node>>`, `InheritableVariable<Handle<Node>>`, `InheritableVariable<Vec<Handle<Node>>>`)
171    /// and automatically maps old handles to new.
172    #[inline]
173    pub fn remap_handles(&self, node: &mut N, ignored_types: &[TypeId]) {
174        let name = node.name().to_string();
175        node.as_reflect_mut(&mut |node| self.remap_handles_internal(node, &name, ignored_types));
176    }
177
178    fn remap_handles_internal(
179        &self,
180        entity: &mut dyn Reflect,
181        node_name: &str,
182        ignored_types: &[TypeId],
183    ) {
184        if ignored_types.contains(&(*entity).type_id()) {
185            return;
186        }
187
188        let mut mapped = false;
189
190        entity.downcast_mut::<Handle<N>>(&mut |handle| {
191            if let Some(handle) = handle {
192                if handle.is_some() && !self.try_map(handle) {
193                    Log::warn(format!(
194                        "Failed to remap handle {} of node {}!",
195                        *handle, node_name
196                    ));
197                }
198                mapped = true;
199            }
200        });
201
202        if mapped {
203            return;
204        }
205
206        entity.downcast_mut::<Vec<Handle<N>>>(&mut |vec| {
207            if let Some(vec) = vec {
208                for handle in vec {
209                    if handle.is_some() && !self.try_map(handle) {
210                        Log::warn(format!(
211                            "Failed to remap handle {} in array of node {}!",
212                            *handle, node_name
213                        ));
214                    }
215                }
216                mapped = true;
217            }
218        });
219
220        if mapped {
221            return;
222        }
223
224        entity.as_inheritable_variable_mut(&mut |inheritable| {
225            if let Some(inheritable) = inheritable {
226                // In case of inheritable variable we must take inner value and do not mark variables as modified.
227                self.remap_handles_internal(
228                    inheritable.inner_value_mut(),
229                    node_name,
230                    ignored_types,
231                );
232
233                mapped = true;
234            }
235        });
236
237        if mapped {
238            return;
239        }
240
241        entity.as_array_mut(&mut |array| {
242            if let Some(array) = array {
243                // Look in every array item.
244                for i in 0..array.reflect_len() {
245                    // Sparse arrays (like Pool) could have empty entries.
246                    if let Some(item) = array.reflect_index_mut(i) {
247                        self.remap_handles_internal(item, node_name, ignored_types);
248                    }
249                }
250                mapped = true;
251            }
252        });
253
254        if mapped {
255            return;
256        }
257
258        entity.as_hash_map_mut(&mut |hash_map| {
259            if let Some(hash_map) = hash_map {
260                for i in 0..hash_map.reflect_len() {
261                    if let Some(item) = hash_map.reflect_get_nth_value_mut(i) {
262                        self.remap_handles_internal(item, node_name, ignored_types);
263                    }
264                }
265                mapped = true;
266            }
267        });
268
269        if mapped {
270            return;
271        }
272
273        // Continue remapping recursively for every compound field.
274        entity.fields_mut(&mut |fields| {
275            for field in fields {
276                field.as_reflect_mut(&mut |field| {
277                    self.remap_handles_internal(field, node_name, ignored_types)
278                })
279            }
280        })
281    }
282
283    #[inline]
284    pub fn remap_inheritable_handles(&self, node: &mut N, ignored_types: &[TypeId]) {
285        let name = node.name().to_string();
286        node.as_reflect_mut(&mut |node| {
287            self.remap_inheritable_handles_internal(node, &name, false, ignored_types)
288        });
289    }
290
291    fn remap_inheritable_handles_internal(
292        &self,
293        entity: &mut dyn Reflect,
294        node_name: &str,
295        do_map: bool,
296        ignored_types: &[TypeId],
297    ) {
298        if ignored_types.contains(&(*entity).type_id()) {
299            return;
300        }
301
302        let mut mapped = false;
303
304        entity.as_inheritable_variable_mut(&mut |result| {
305            if let Some(inheritable) = result {
306                // In case of inheritable variable we must take inner value and do not mark variables as modified.
307                if !inheritable.is_modified() {
308                    self.remap_inheritable_handles_internal(
309                        inheritable.inner_value_mut(),
310                        node_name,
311                        // Raise mapping flag, any handle in inner value will be mapped. The flag is propagated
312                        // to unlimited depth.
313                        true,
314                        ignored_types,
315                    );
316                }
317                mapped = true;
318            }
319        });
320
321        if mapped {
322            return;
323        }
324
325        entity.downcast_mut::<Handle<N>>(&mut |result| {
326            if let Some(handle) = result {
327                if do_map && handle.is_some() && !self.try_map(handle) {
328                    Log::warn(format!(
329                        "Failed to remap handle {} of node {}!",
330                        *handle, node_name
331                    ));
332                }
333                mapped = true;
334            }
335        });
336
337        if mapped {
338            return;
339        }
340
341        entity.downcast_mut::<Vec<Handle<N>>>(&mut |result| {
342            if let Some(vec) = result {
343                if do_map {
344                    for handle in vec {
345                        if handle.is_some() && !self.try_map(handle) {
346                            Log::warn(format!(
347                                "Failed to remap handle {} in array of node {}!",
348                                *handle, node_name
349                            ));
350                        }
351                    }
352                }
353                mapped = true;
354            }
355        });
356
357        if mapped {
358            return;
359        }
360
361        entity.as_array_mut(&mut |result| {
362            if let Some(array) = result {
363                // Look in every array item.
364                for i in 0..array.reflect_len() {
365                    // Sparse arrays (like Pool) could have empty entries.
366                    if let Some(item) = array.reflect_index_mut(i) {
367                        self.remap_inheritable_handles_internal(
368                            item,
369                            node_name,
370                            // Propagate mapping flag - it means that we're inside inheritable variable. In this
371                            // case we will map handles.
372                            do_map,
373                            ignored_types,
374                        );
375                    }
376                }
377                mapped = true;
378            }
379        });
380
381        if mapped {
382            return;
383        }
384
385        entity.as_hash_map_mut(&mut |result| {
386            if let Some(hash_map) = result {
387                for i in 0..hash_map.reflect_len() {
388                    if let Some(item) = hash_map.reflect_get_nth_value_mut(i) {
389                        self.remap_inheritable_handles_internal(
390                            item,
391                            node_name,
392                            // Propagate mapping flag - it means that we're inside inheritable variable. In this
393                            // case we will map handles.
394                            do_map,
395                            ignored_types,
396                        );
397                    }
398                }
399                mapped = true;
400            }
401        });
402
403        if mapped {
404            return;
405        }
406
407        // Continue remapping recursively for every compound field.
408        entity.fields_mut(&mut |fields| {
409            for field in fields {
410                self.remap_inheritable_handles_internal(
411                    *field,
412                    node_name,
413                    // Propagate mapping flag - it means that we're inside inheritable variable. In this
414                    // case we will map handles.
415                    do_map,
416                    ignored_types,
417                );
418            }
419        })
420    }
421}
422
423fn reset_property_modified_flag(entity: &mut dyn Reflect, path: &str) {
424    entity.as_reflect_mut(&mut |entity| {
425        entity.resolve_path_mut(path, &mut |result| {
426            variable::mark_inheritable_properties_non_modified(
427                result.unwrap(),
428                &[TypeId::of::<UntypedResource>()],
429            );
430        })
431    })
432}
433
434pub trait AbstractSceneNode: ComponentProvider + Reflect + NameProvider {}
435
436impl<T: SceneGraphNode> AbstractSceneNode for T {}
437
438pub trait SceneGraphNode: AbstractSceneNode + Clone + 'static {
439    type Base: Clone;
440    type SceneGraph: SceneGraph<Node = Self>;
441    type ResourceData: PrefabData<Graph = Self::SceneGraph>;
442
443    fn base(&self) -> &Self::Base;
444    fn set_base(&mut self, base: Self::Base);
445    fn is_resource_instance_root(&self) -> bool;
446    fn original_handle_in_resource(&self) -> Handle<Self>;
447    fn set_original_handle_in_resource(&mut self, handle: Handle<Self>);
448    fn resource(&self) -> Option<Resource<Self::ResourceData>>;
449    fn self_handle(&self) -> Handle<Self>;
450    fn parent(&self) -> Handle<Self>;
451    fn children(&self) -> &[Handle<Self>];
452    fn children_mut(&mut self) -> &mut [Handle<Self>];
453
454    /// Puts the given `child` handle to the given position `pos`, by swapping positions.
455    #[inline]
456    fn swap_child_position(&mut self, child: Handle<Self>, pos: usize) -> Option<usize> {
457        let children = self.children_mut();
458
459        if pos >= children.len() {
460            return None;
461        }
462
463        if let Some(current_position) = children.iter().position(|c| *c == child) {
464            children.swap(current_position, pos);
465
466            Some(current_position)
467        } else {
468            None
469        }
470    }
471
472    #[inline]
473    fn set_child_position(&mut self, child: Handle<Self>, dest_pos: usize) -> Option<usize> {
474        let children = self.children_mut();
475
476        if dest_pos >= children.len() {
477            return None;
478        }
479
480        if let Some(mut current_position) = children.iter().position(|c| *c == child) {
481            let prev_position = current_position;
482
483            match current_position.cmp(&dest_pos) {
484                Ordering::Less => {
485                    while current_position != dest_pos {
486                        let next = current_position.saturating_add(1);
487                        children.swap(current_position, next);
488                        current_position = next;
489                    }
490                }
491                Ordering::Equal => {}
492                Ordering::Greater => {
493                    while current_position != dest_pos {
494                        let prev = current_position.saturating_sub(1);
495                        children.swap(current_position, prev);
496                        current_position = prev;
497                    }
498                }
499            }
500
501            Some(prev_position)
502        } else {
503            None
504        }
505    }
506
507    #[inline]
508    fn child_position(&self, child: Handle<Self>) -> Option<usize> {
509        self.children().iter().position(|c| *c == child)
510    }
511
512    #[inline]
513    fn has_child(&self, child: Handle<Self>) -> bool {
514        self.children().contains(&child)
515    }
516
517    fn revert_inheritable_property(&mut self, path: &str) -> Option<Box<dyn Reflect>> {
518        let mut previous_value = None;
519
520        // Revert only if there's parent resource (the node is an instance of some resource).
521        if let Some(resource) = self.resource().as_ref() {
522            let resource_data = resource.data_ref();
523            let parent = &resource_data
524                .graph()
525                .node(self.original_handle_in_resource());
526
527            let mut parent_value = None;
528
529            // Find and clone parent's value first.
530            parent.as_reflect(&mut |parent| {
531                parent.resolve_path(path, &mut |result| match result {
532                    Ok(parent_field) => parent_field.as_inheritable_variable(&mut |parent_field| {
533                        if let Some(parent_inheritable) = parent_field {
534                            parent_value = Some(parent_inheritable.clone_value_box());
535                        }
536                    }),
537                    Err(e) => Log::err(format!(
538                        "Failed to resolve parent path {path}. Reason: {e:?}"
539                    )),
540                })
541            });
542
543            // Check whether the child's field is inheritable and modified.
544            let mut need_revert = false;
545
546            self.as_reflect_mut(&mut |child| {
547                child.resolve_path_mut(path, &mut |result| match result {
548                    Ok(child_field) => {
549                        child_field.as_inheritable_variable_mut(&mut |child_inheritable| {
550                            if let Some(child_inheritable) = child_inheritable {
551                                need_revert = child_inheritable.is_modified();
552                            } else {
553                                Log::err(format!("Property {path} is not inheritable!"))
554                            }
555                        })
556                    }
557                    Err(e) => Log::err(format!(
558                        "Failed to resolve child path {path}. Reason: {e:?}"
559                    )),
560                });
561            });
562
563            // Try to apply it to the child.
564            if need_revert {
565                if let Some(parent_value) = parent_value {
566                    let mut was_set = false;
567
568                    let mut parent_value = Some(parent_value);
569                    self.as_reflect_mut(&mut |child| {
570                        child.set_field_by_path(
571                            path,
572                            parent_value.take().unwrap(),
573                            &mut |result| match result {
574                                Ok(old_value) => {
575                                    previous_value = Some(old_value);
576
577                                    was_set = true;
578                                }
579                                Err(_) => Log::err(format!(
580                                    "Failed to revert property {path}. Reason: no such property!"
581                                )),
582                            },
583                        );
584                    });
585
586                    if was_set {
587                        // Reset modified flag.
588                        reset_property_modified_flag(self, path);
589                    }
590                }
591            }
592        }
593
594        previous_value
595    }
596
597    /// Tries to borrow a component of given type.
598    #[inline]
599    fn component_ref<T: Any>(&self) -> Option<&T> {
600        ComponentProvider::query_component_ref(self, TypeId::of::<T>())
601            .and_then(|c| c.downcast_ref())
602    }
603
604    /// Tries to borrow a component of given type.
605    #[inline]
606    fn component_mut<T: Any>(&mut self) -> Option<&mut T> {
607        ComponentProvider::query_component_mut(self, TypeId::of::<T>())
608            .and_then(|c| c.downcast_mut())
609    }
610
611    /// Checks if the node has a component of given type.
612    #[inline]
613    fn has_component<T: Any>(&self) -> bool {
614        self.component_ref::<T>().is_some()
615    }
616}
617
618pub trait PrefabData: TypedResourceData + 'static {
619    type Graph: SceneGraph;
620
621    fn graph(&self) -> &Self::Graph;
622    fn mapping(&self) -> NodeMapping;
623}
624
625#[derive(Debug)]
626pub struct LinkScheme<N> {
627    pub root: Handle<N>,
628    pub links: Vec<(Handle<N>, Handle<N>)>,
629}
630
631impl<N> Default for LinkScheme<N> {
632    fn default() -> Self {
633        Self {
634            root: Default::default(),
635            links: Default::default(),
636        }
637    }
638}
639
640pub trait AbstractSceneGraph: 'static {
641    fn try_get_node_untyped(&self, handle: ErasedHandle) -> Option<&dyn AbstractSceneNode>;
642    fn try_get_node_untyped_mut(
643        &mut self,
644        handle: ErasedHandle,
645    ) -> Option<&mut dyn AbstractSceneNode>;
646}
647
648pub trait BaseSceneGraph: AbstractSceneGraph {
649    type Prefab: PrefabData<Graph = Self>;
650    type Node: SceneGraphNode<SceneGraph = Self, ResourceData = Self::Prefab>;
651
652    /// Returns a handle of the root node of the graph.
653    fn root(&self) -> Handle<Self::Node>;
654
655    /// Sets the new root of the graph. If used incorrectly, it may create isolated sub-graphs.
656    fn set_root(&mut self, root: Handle<Self::Node>);
657
658    /// Tries to borrow a node, returns Some(node) if the handle is valid, None - otherwise.
659    fn try_get(&self, handle: Handle<Self::Node>) -> Option<&Self::Node>;
660
661    /// Tries to borrow a node, returns Some(node) if the handle is valid, None - otherwise.
662    fn try_get_mut(&mut self, handle: Handle<Self::Node>) -> Option<&mut Self::Node>;
663
664    /// Checks whether the given node handle is valid or not.
665    fn is_valid_handle(&self, handle: Handle<Self::Node>) -> bool;
666
667    /// Adds a new node to the graph.
668    fn add_node(&mut self, node: Self::Node) -> Handle<Self::Node>;
669
670    /// Destroys the node and its children recursively.
671    fn remove_node(&mut self, node_handle: Handle<Self::Node>);
672
673    /// Links specified child with specified parent.
674    fn link_nodes(&mut self, child: Handle<Self::Node>, parent: Handle<Self::Node>);
675
676    /// Unlinks specified node from its parent and attaches it to root graph node.
677    fn unlink_node(&mut self, node_handle: Handle<Self::Node>);
678
679    /// Detaches the node from its parent, making the node unreachable from any other node in the
680    /// graph.
681    fn isolate_node(&mut self, node_handle: Handle<Self::Node>);
682
683    /// Borrows a node by its handle.
684    fn node(&self, handle: Handle<Self::Node>) -> &Self::Node {
685        self.try_get(handle).expect("The handle must be valid!")
686    }
687
688    /// Borrows a node by its handle.
689    fn node_mut(&mut self, handle: Handle<Self::Node>) -> &mut Self::Node {
690        self.try_get_mut(handle).expect("The handle must be valid!")
691    }
692
693    /// Reorders the node hierarchy so the `new_root` becomes the root node for the entire hierarchy
694    /// under the `prev_root` node. For example, if we have this hierarchy and want to set `C` as
695    /// the new root:
696    ///
697    /// ```text
698    /// Root_
699    ///      |_A_
700    ///          |_B
701    ///          |_C_
702    ///             |_D
703    /// ```
704    ///
705    /// The new hierarchy will become:
706    ///
707    /// ```text
708    /// C_
709    ///   |_D
710    ///   |_A_
711    ///   |   |_B
712    ///   |_Root
713    /// ```    
714    ///
715    /// This method returns an instance of [`LinkScheme`], that could be used to revert the hierarchy
716    /// back to its original. See [`Self::apply_link_scheme`] for more info.
717    #[inline]
718    #[allow(clippy::unnecessary_to_owned)] // False-positive
719    fn change_hierarchy_root(
720        &mut self,
721        prev_root: Handle<Self::Node>,
722        new_root: Handle<Self::Node>,
723    ) -> LinkScheme<Self::Node> {
724        let mut scheme = LinkScheme::default();
725
726        if prev_root == new_root {
727            return scheme;
728        }
729
730        scheme
731            .links
732            .push((prev_root, self.node(prev_root).parent()));
733
734        scheme.links.push((new_root, self.node(new_root).parent()));
735
736        self.isolate_node(new_root);
737
738        for prev_root_child in self.node(prev_root).children().to_vec() {
739            self.link_nodes(prev_root_child, new_root);
740            scheme.links.push((prev_root_child, prev_root));
741        }
742
743        self.link_nodes(prev_root, new_root);
744
745        if prev_root == self.root() {
746            self.set_root(new_root);
747            scheme.root = prev_root;
748        } else {
749            scheme.root = self.root();
750        }
751
752        scheme
753    }
754
755    /// Applies the given link scheme to the graph, basically reverting graph structure to the one
756    /// that was before the call of [`Self::change_hierarchy_root`].
757    #[inline]
758    fn apply_link_scheme(&mut self, mut scheme: LinkScheme<Self::Node>) {
759        for (child, parent) in scheme.links.drain(..) {
760            if parent.is_some() {
761                self.link_nodes(child, parent);
762            } else {
763                self.isolate_node(child);
764            }
765        }
766        if scheme.root.is_some() {
767            self.set_root(scheme.root);
768        }
769    }
770
771    /// Removes all the nodes from the given slice.
772    #[inline]
773    fn remove_nodes(&mut self, nodes: &[Handle<Self::Node>]) {
774        for &node in nodes {
775            if self.is_valid_handle(node) {
776                self.remove_node(node)
777            }
778        }
779    }
780}
781
782pub trait SceneGraph: BaseSceneGraph {
783    /// Creates new iterator that iterates over internal collection giving (handle; node) pairs.
784    fn pair_iter(&self) -> impl Iterator<Item = (Handle<Self::Node>, &Self::Node)>;
785
786    /// Creates an iterator that has linear iteration order over internal collection
787    /// of nodes. It does *not* perform any tree traversal!
788    fn linear_iter(&self) -> impl Iterator<Item = &Self::Node>;
789
790    /// Creates an iterator that has linear iteration order over internal collection
791    /// of nodes. It does *not* perform any tree traversal!
792    fn linear_iter_mut(&mut self) -> impl Iterator<Item = &mut Self::Node>;
793
794    /// Tries to borrow a node and fetch its component of specified type.
795    #[inline]
796    fn try_get_of_type<T>(&self, handle: Handle<Self::Node>) -> Option<&T>
797    where
798        T: 'static,
799    {
800        self.try_get(handle)
801            .and_then(|n| n.query_component_ref(TypeId::of::<T>()))
802            .and_then(|c| c.downcast_ref())
803    }
804
805    /// Tries to mutably borrow a node and fetch its component of specified type.
806    #[inline]
807    fn try_get_mut_of_type<T>(&mut self, handle: Handle<Self::Node>) -> Option<&mut T>
808    where
809        T: 'static,
810    {
811        self.try_get_mut(handle)
812            .and_then(|n| n.query_component_mut(TypeId::of::<T>()))
813            .and_then(|c| c.downcast_mut())
814    }
815
816    /// Tries to borrow a node by the given handle and checks if it has a component of the specified
817    /// type.
818    #[inline]
819    fn has_component<T>(&self, handle: Handle<Self::Node>) -> bool
820    where
821        T: 'static,
822    {
823        self.try_get_of_type::<T>(handle).is_some()
824    }
825
826    /// Searches for a node down the tree starting from the specified node using the specified closure. Returns a tuple
827    /// with a handle and a reference to the mapped value. If nothing is found, it returns [`None`].
828    #[inline]
829    fn find_map<C, T>(
830        &self,
831        root_node: Handle<Self::Node>,
832        cmp: &mut C,
833    ) -> Option<(Handle<Self::Node>, &T)>
834    where
835        C: FnMut(&Self::Node) -> Option<&T>,
836        T: ?Sized,
837    {
838        self.try_get(root_node).and_then(|root| {
839            if let Some(x) = cmp(root) {
840                Some((root_node, x))
841            } else {
842                root.children().iter().find_map(|c| self.find_map(*c, cmp))
843            }
844        })
845    }
846
847    /// Searches for a node up the tree starting from the specified node using the specified closure. Returns a tuple
848    /// with a handle and a reference to the found node. If nothing is found, it returns [`None`].
849    #[inline]
850    fn find_up<C>(
851        &self,
852        root_node: Handle<Self::Node>,
853        cmp: &mut C,
854    ) -> Option<(Handle<Self::Node>, &Self::Node)>
855    where
856        C: FnMut(&Self::Node) -> bool,
857    {
858        let mut handle = root_node;
859        while let Some(node) = self.try_get(handle) {
860            if cmp(node) {
861                return Some((handle, node));
862            }
863            handle = node.parent();
864        }
865        None
866    }
867
868    /// The same as [`Self::find_up`], but only returns node handle which will be [`Handle::NONE`]
869    /// if nothing is found.
870    #[inline]
871    fn find_handle_up<C>(&self, root_node: Handle<Self::Node>, cmp: &mut C) -> Handle<Self::Node>
872    where
873        C: FnMut(&Self::Node) -> bool,
874    {
875        self.find_up(root_node, cmp)
876            .map(|(h, _)| h)
877            .unwrap_or_default()
878    }
879
880    #[inline]
881    fn find_component_up<T>(
882        &self,
883        node_handle: Handle<Self::Node>,
884    ) -> Option<(Handle<Self::Node>, &T)>
885    where
886        T: 'static,
887    {
888        self.find_up_map(node_handle, &mut |node| {
889            node.query_component_ref(TypeId::of::<T>())
890        })
891        .and_then(|(handle, c)| c.downcast_ref::<T>().map(|typed| (handle, typed)))
892    }
893
894    #[inline]
895    fn find_component<T>(&self, node_handle: Handle<Self::Node>) -> Option<(Handle<Self::Node>, &T)>
896    where
897        T: 'static,
898    {
899        self.find_map(node_handle, &mut |node| {
900            node.query_component_ref(TypeId::of::<T>())
901        })
902        .and_then(|(handle, c)| c.downcast_ref::<T>().map(|typed| (handle, typed)))
903    }
904
905    /// Searches for a node up the tree starting from the specified node using the specified closure. Returns a tuple
906    /// with a handle and a reference to the mapped value. If nothing is found, it returns [`None`].
907    #[inline]
908    fn find_up_map<C, T>(
909        &self,
910        root_node: Handle<Self::Node>,
911        cmp: &mut C,
912    ) -> Option<(Handle<Self::Node>, &T)>
913    where
914        C: FnMut(&Self::Node) -> Option<&T>,
915        T: ?Sized,
916    {
917        let mut handle = root_node;
918        while let Some(node) = self.try_get(handle) {
919            if let Some(x) = cmp(node) {
920                return Some((handle, x));
921            }
922            handle = node.parent();
923        }
924        None
925    }
926
927    /// Searches for a node with the specified name down the tree starting from the specified node. Returns a tuple with
928    /// a handle and a reference to the found node. If nothing is found, it returns [`None`].
929    #[inline]
930    fn find_by_name(
931        &self,
932        root_node: Handle<Self::Node>,
933        name: &str,
934    ) -> Option<(Handle<Self::Node>, &Self::Node)> {
935        self.find(root_node, &mut |node| node.name() == name)
936    }
937
938    /// Searches for a node with the specified name up the tree starting from the specified node. Returns a tuple with a
939    /// handle and a reference to the found node. If nothing is found, it returns [`None`].
940    #[inline]
941    fn find_up_by_name(
942        &self,
943        root_node: Handle<Self::Node>,
944        name: &str,
945    ) -> Option<(Handle<Self::Node>, &Self::Node)> {
946        self.find_up(root_node, &mut |node| node.name() == name)
947    }
948
949    /// Searches for a node with the specified name down the tree starting from the graph root. Returns a tuple with a
950    /// handle and a reference to the found node. If nothing is found, it returns [`None`].
951    #[inline]
952    fn find_by_name_from_root(&self, name: &str) -> Option<(Handle<Self::Node>, &Self::Node)> {
953        self.find_by_name(self.root(), name)
954    }
955
956    #[inline]
957    fn find_handle_by_name_from_root(&self, name: &str) -> Handle<Self::Node> {
958        self.find_by_name(self.root(), name)
959            .map(|(h, _)| h)
960            .unwrap_or_default()
961    }
962
963    /// Searches node using specified compare closure starting from root. Returns a tuple with a handle and
964    /// a reference to the found node. If nothing is found, it returns [`None`].
965    #[inline]
966    fn find_from_root<C>(&self, cmp: &mut C) -> Option<(Handle<Self::Node>, &Self::Node)>
967    where
968        C: FnMut(&Self::Node) -> bool,
969    {
970        self.find(self.root(), cmp)
971    }
972
973    /// Searches for a node down the tree starting from the specified node using the specified closure.
974    /// Returns a tuple with a handle and a reference to the found node. If nothing is found, it
975    /// returns [`None`].
976    #[inline]
977    fn find<C>(
978        &self,
979        root_node: Handle<Self::Node>,
980        cmp: &mut C,
981    ) -> Option<(Handle<Self::Node>, &Self::Node)>
982    where
983        C: FnMut(&Self::Node) -> bool,
984    {
985        self.try_get(root_node).and_then(|root| {
986            if cmp(root) {
987                Some((root_node, root))
988            } else {
989                root.children().iter().find_map(|c| self.find(*c, cmp))
990            }
991        })
992    }
993
994    /// The same as [`Self::find`], but only returns node handle which will be [`Handle::NONE`]
995    /// if nothing is found.
996    #[inline]
997    fn find_handle<C>(&self, root_node: Handle<Self::Node>, cmp: &mut C) -> Handle<Self::Node>
998    where
999        C: FnMut(&Self::Node) -> bool,
1000    {
1001        self.find(root_node, cmp)
1002            .map(|(h, _)| h)
1003            .unwrap_or_default()
1004    }
1005
1006    /// Returns position of the node in its parent children list and the handle to the parent. Adds
1007    /// given `offset` to the position. For example, if you have the following hierarchy:
1008    ///
1009    /// ```text
1010    /// A_
1011    ///  |B
1012    ///  |C
1013    /// ```
1014    ///
1015    /// Calling this method with a handle of `C` will return `Some((handle_of(A), 1))`. The returned
1016    /// value will be clamped in the `0..parent_child_count` range. `None` will be returned only if
1017    /// the given handle is invalid, or it is the root node.
1018    #[inline]
1019    fn relative_position(
1020        &self,
1021        child: Handle<Self::Node>,
1022        offset: isize,
1023    ) -> Option<(Handle<Self::Node>, usize)> {
1024        let parents_parent_handle = self.try_get(child)?.parent();
1025        let parents_parent_ref = self.try_get(parents_parent_handle)?;
1026        let position = parents_parent_ref.child_position(child)?;
1027        Some((
1028            parents_parent_handle,
1029            ((position as isize + offset) as usize).clamp(0, parents_parent_ref.children().len()),
1030        ))
1031    }
1032
1033    /// Create a graph depth traversal iterator.
1034    #[inline]
1035    fn traverse_iter(
1036        &self,
1037        from: Handle<Self::Node>,
1038    ) -> impl Iterator<Item = (Handle<Self::Node>, &Self::Node)> {
1039        GraphTraverseIterator {
1040            graph: self,
1041            stack: vec![from],
1042        }
1043    }
1044
1045    /// Create a graph depth traversal iterator.
1046    #[inline]
1047    fn traverse_handle_iter(
1048        &self,
1049        from: Handle<Self::Node>,
1050    ) -> impl Iterator<Item = Handle<Self::Node>> {
1051        self.traverse_iter(from).map(|(handle, _)| handle)
1052    }
1053
1054    /// This method checks integrity of the graph and restores it if needed. For example, if a node
1055    /// was added in a parent asset, then it must be added in the graph. Alternatively, if a node was
1056    /// deleted in a parent asset, then its instance must be deleted in the graph.
1057    fn restore_integrity<F>(
1058        &mut self,
1059        mut instantiate: F,
1060    ) -> Vec<(Handle<Self::Node>, Resource<Self::Prefab>)>
1061    where
1062        F: FnMut(
1063            Resource<Self::Prefab>,
1064            &Self::Prefab,
1065            Handle<Self::Node>,
1066            &mut Self,
1067        ) -> (Handle<Self::Node>, NodeHandleMap<Self::Node>),
1068    {
1069        Log::writeln(MessageKind::Information, "Checking integrity...");
1070
1071        let instances = self
1072            .pair_iter()
1073            .filter_map(|(h, n)| {
1074                if n.is_resource_instance_root() {
1075                    Some((h, n.resource().unwrap()))
1076                } else {
1077                    None
1078                }
1079            })
1080            .collect::<Vec<_>>();
1081
1082        let instance_count = instances.len();
1083        let mut restored_count = 0;
1084
1085        for (instance_root, resource) in instances.iter().cloned() {
1086            // Step 1. Find and remove orphaned nodes.
1087            let mut nodes_to_delete = Vec::new();
1088            for (_, node) in self.traverse_iter(instance_root) {
1089                if let Some(resource) = node.resource() {
1090                    let kind = resource.kind().clone();
1091                    if let Some(model) = resource.state().data() {
1092                        if !model
1093                            .graph()
1094                            .is_valid_handle(node.original_handle_in_resource())
1095                        {
1096                            nodes_to_delete.push(node.self_handle());
1097
1098                            Log::warn(format!(
1099                                "Node {} ({}:{}) and its children will be deleted, because it \
1100                    does not exist in the parent asset `{}`!",
1101                                node.name(),
1102                                node.self_handle().index(),
1103                                node.self_handle().generation(),
1104                                kind
1105                            ))
1106                        }
1107                    } else {
1108                        Log::warn(format!(
1109                            "Node {} ({}:{}) and its children will be deleted, because its \
1110                    parent asset `{}` failed to load!",
1111                            node.name(),
1112                            node.self_handle().index(),
1113                            node.self_handle().generation(),
1114                            kind
1115                        ))
1116                    }
1117                }
1118            }
1119
1120            for node_to_delete in nodes_to_delete {
1121                if self.is_valid_handle(node_to_delete) {
1122                    self.remove_node(node_to_delete);
1123                }
1124            }
1125
1126            // Step 2. Look for missing nodes and create appropriate instances for them.
1127            let mut model = resource.state();
1128            let model_kind = model.kind().clone();
1129            if let Some(data) = model.data() {
1130                let resource_graph = data.graph();
1131
1132                let resource_instance_root = self.node(instance_root).original_handle_in_resource();
1133
1134                if resource_instance_root.is_none() {
1135                    let instance = self.node(instance_root);
1136                    Log::writeln(
1137                        MessageKind::Warning,
1138                        format!(
1139                            "There is an instance of resource {} \
1140                    but original node {} cannot be found!",
1141                            model_kind,
1142                            instance.name()
1143                        ),
1144                    );
1145
1146                    continue;
1147                }
1148
1149                let mut traverse_stack = vec![resource_instance_root];
1150                while let Some(resource_node_handle) = traverse_stack.pop() {
1151                    let resource_node = resource_graph.node(resource_node_handle);
1152
1153                    // Root of the resource is not belongs to resource, it is just a convenient way of
1154                    // consolidation all descendants under a single node.
1155                    let mut compare =
1156                        |n: &Self::Node| n.original_handle_in_resource() == resource_node_handle;
1157
1158                    if resource_node_handle != resource_graph.root()
1159                        && self.find(instance_root, &mut compare).is_none()
1160                    {
1161                        Log::writeln(
1162                            MessageKind::Warning,
1163                            format!(
1164                                "Instance of node {} is missing. Restoring integrity...",
1165                                resource_node.name()
1166                            ),
1167                        );
1168
1169                        // Instantiate missing node.
1170                        let (copy, old_to_new_mapping) =
1171                            instantiate(resource.clone(), data, resource_node_handle, self);
1172
1173                        restored_count += old_to_new_mapping.inner().len();
1174
1175                        // Link it with existing node.
1176                        if resource_node.parent().is_some() {
1177                            let parent = self.find(instance_root, &mut |n| {
1178                                n.original_handle_in_resource() == resource_node.parent()
1179                            });
1180
1181                            if let Some((parent_handle, _)) = parent {
1182                                self.link_nodes(copy, parent_handle);
1183                            } else {
1184                                // Fail-safe route - link with root of instance.
1185                                self.link_nodes(copy, instance_root);
1186                            }
1187                        } else {
1188                            // Fail-safe route - link with root of instance.
1189                            self.link_nodes(copy, instance_root);
1190                        }
1191                    }
1192
1193                    traverse_stack.extend_from_slice(resource_node.children());
1194                }
1195            }
1196        }
1197
1198        Log::writeln(
1199            MessageKind::Information,
1200            format!(
1201                "Integrity restored for {instance_count} instances! {restored_count} new nodes were added!"
1202            ),
1203        );
1204
1205        instances
1206    }
1207
1208    fn restore_original_handles_and_inherit_properties<F>(
1209        &mut self,
1210        ignored_types: &[TypeId],
1211        mut before_inherit: F,
1212    ) where
1213        F: FnMut(&Self::Node, &mut Self::Node),
1214    {
1215        let mut ignored_types = ignored_types.to_vec();
1216        // Do not try to inspect resources, because it most likely cause a deadlock.
1217        ignored_types.push(TypeId::of::<UntypedResource>());
1218
1219        // Iterate over each node in the graph and resolve original handles. Original handle is a handle
1220        // to a node in resource from which a node was instantiated from. Also sync inheritable properties
1221        // if needed.
1222        for node in self.linear_iter_mut() {
1223            if let Some(model) = node.resource() {
1224                let mut header = model.state();
1225                let model_kind = header.kind().clone();
1226                if let Some(data) = header.data() {
1227                    let resource_graph = data.graph();
1228
1229                    let resource_node = match data.mapping() {
1230                        NodeMapping::UseNames => {
1231                            // For some models we can resolve it only by names of nodes, but this is not
1232                            // reliable way of doing this, because some editors allow nodes to have same
1233                            // names for objects, but here we'll assume that modellers will not create
1234                            // models with duplicated names and user of the engine reads log messages.
1235                            resource_graph
1236                                .pair_iter()
1237                                .find_map(|(handle, resource_node)| {
1238                                    if resource_node.name() == node.name() {
1239                                        Some((resource_node, handle))
1240                                    } else {
1241                                        None
1242                                    }
1243                                })
1244                        }
1245                        NodeMapping::UseHandles => {
1246                            // Use original handle directly.
1247                            resource_graph
1248                                .try_get(node.original_handle_in_resource())
1249                                .map(|resource_node| {
1250                                    (resource_node, node.original_handle_in_resource())
1251                                })
1252                        }
1253                    };
1254
1255                    if let Some((resource_node, original)) = resource_node {
1256                        node.set_original_handle_in_resource(original);
1257
1258                        before_inherit(resource_node, node);
1259
1260                        // Check if the actual node types (this and parent's) are equal, and if not - copy the
1261                        // node and replace its base.
1262                        let mut types_match = true;
1263                        node.as_reflect(&mut |node_reflect| {
1264                            resource_node.as_reflect(&mut |resource_node_reflect| {
1265                                types_match =
1266                                    node_reflect.type_id() == resource_node_reflect.type_id();
1267
1268                                if !types_match {
1269                                    Log::warn(format!(
1270                                        "Node {}({}:{}) instance \
1271                                        have different type than in the respective parent \
1272                                        asset {}. The type will be fixed.",
1273                                        node.name(),
1274                                        node.self_handle().index(),
1275                                        node.self_handle().generation(),
1276                                        model_kind
1277                                    ));
1278                                }
1279                            })
1280                        });
1281                        if !types_match {
1282                            let base = node.base().clone();
1283                            let mut resource_node_clone = resource_node.clone();
1284                            variable::mark_inheritable_properties_non_modified(
1285                                &mut resource_node_clone as &mut dyn Reflect,
1286                                &ignored_types,
1287                            );
1288                            resource_node_clone.set_base(base);
1289                            *node = resource_node_clone;
1290                        }
1291
1292                        // Then try to inherit properties.
1293                        node.as_reflect_mut(&mut |node_reflect| {
1294                            resource_node.as_reflect(&mut |resource_node_reflect| {
1295                                Log::verify(variable::try_inherit_properties(
1296                                    node_reflect,
1297                                    resource_node_reflect,
1298                                    &ignored_types,
1299                                ));
1300                            })
1301                        })
1302                    } else {
1303                        Log::warn(format!(
1304                            "Unable to find original handle for node {}. The node will be removed!",
1305                            node.name(),
1306                        ))
1307                    }
1308                }
1309            }
1310        }
1311
1312        Log::writeln(MessageKind::Information, "Original handles resolved!");
1313    }
1314
1315    /// Maps handles in properties of instances after property inheritance. It is needed, because when a
1316    /// property contains node handle, the handle cannot be used directly after inheritance. Instead, it
1317    /// must be mapped to respective instance first.
1318    ///
1319    /// To do so, we at first, build node handle mapping (original handle -> instance handle) starting from
1320    /// instance root. Then we must find all inheritable properties and try to remap them to instance handles.
1321    fn remap_handles(&mut self, instances: &[(Handle<Self::Node>, Resource<Self::Prefab>)]) {
1322        for (instance_root, resource) in instances {
1323            // Prepare old -> new handle mapping first by walking over the graph
1324            // starting from instance root.
1325            let mut old_new_mapping = NodeHandleMap::default();
1326            let mut traverse_stack = vec![*instance_root];
1327            while let Some(node_handle) = traverse_stack.pop() {
1328                let node = self.node(node_handle);
1329                if let Some(node_resource) = node.resource().as_ref() {
1330                    // We're interested only in instance nodes.
1331                    if node_resource == resource {
1332                        let previous_mapping =
1333                            old_new_mapping.insert(node.original_handle_in_resource(), node_handle);
1334                        // There should be no such node.
1335                        if previous_mapping.is_some() {
1336                            Log::warn(format!(
1337                                "There are multiple original nodes for {:?}! Previous was {:?}. \
1338                                This can happen if a respective node was deleted.",
1339                                node_handle,
1340                                node.original_handle_in_resource()
1341                            ))
1342                        }
1343                    }
1344                }
1345
1346                traverse_stack.extend_from_slice(node.children());
1347            }
1348
1349            // Lastly, remap handles. We can't do this in single pass because there could
1350            // be cross references.
1351            for (_, handle) in old_new_mapping.inner().iter() {
1352                old_new_mapping.remap_inheritable_handles(
1353                    self.node_mut(*handle),
1354                    &[TypeId::of::<UntypedResource>()],
1355                );
1356            }
1357        }
1358    }
1359}
1360
1361/// Iterator that traverses tree in depth and returns shared references to nodes.
1362pub struct GraphTraverseIterator<'a, G: ?Sized, N> {
1363    graph: &'a G,
1364    stack: Vec<Handle<N>>,
1365}
1366
1367impl<'a, G: ?Sized, N> Iterator for GraphTraverseIterator<'a, G, N>
1368where
1369    G: SceneGraph<Node = N>,
1370    N: SceneGraphNode,
1371{
1372    type Item = (Handle<N>, &'a N);
1373
1374    #[inline]
1375    fn next(&mut self) -> Option<Self::Item> {
1376        if let Some(handle) = self.stack.pop() {
1377            let node = self.graph.node(handle);
1378
1379            for child_handle in node.children() {
1380                self.stack.push(*child_handle);
1381            }
1382
1383            return Some((handle, node));
1384        }
1385
1386        None
1387    }
1388}
1389
1390#[cfg(test)]
1391mod test {
1392    use crate::{
1393        AbstractSceneGraph, AbstractSceneNode, BaseSceneGraph, NodeMapping, PrefabData, SceneGraph,
1394        SceneGraphNode,
1395    };
1396    use fyrox_core::pool::ErasedHandle;
1397    use fyrox_core::{
1398        pool::{Handle, Pool},
1399        reflect::prelude::*,
1400        type_traits::prelude::*,
1401        visitor::prelude::*,
1402        NameProvider,
1403    };
1404    use fyrox_resource::{Resource, ResourceData};
1405    use std::{
1406        error::Error,
1407        ops::{Deref, DerefMut, Index, IndexMut},
1408        path::Path,
1409    };
1410
1411    #[derive(Default, Visit, Reflect, Debug, Clone)]
1412    struct Base {
1413        name: String,
1414        self_handle: Handle<Node>,
1415        is_resource_instance_root: bool,
1416        original_handle_in_resource: Handle<Node>,
1417        resource: Option<Resource<Graph>>,
1418        parent: Handle<Node>,
1419        children: Vec<Handle<Node>>,
1420    }
1421
1422    #[derive(Clone, ComponentProvider, Visit, Reflect, Debug, Default)]
1423    struct Node {
1424        base: Base,
1425    }
1426
1427    impl NameProvider for Node {
1428        fn name(&self) -> &str {
1429            &self.base.name
1430        }
1431    }
1432
1433    impl Deref for Node {
1434        type Target = Base;
1435
1436        fn deref(&self) -> &Self::Target {
1437            &self.base
1438        }
1439    }
1440
1441    impl DerefMut for Node {
1442        fn deref_mut(&mut self) -> &mut Self::Target {
1443            &mut self.base
1444        }
1445    }
1446
1447    impl SceneGraphNode for Node {
1448        type Base = Base;
1449        type SceneGraph = Graph;
1450        type ResourceData = Graph;
1451
1452        fn base(&self) -> &Self::Base {
1453            &self.base
1454        }
1455
1456        fn set_base(&mut self, base: Self::Base) {
1457            self.base = base;
1458        }
1459
1460        fn is_resource_instance_root(&self) -> bool {
1461            self.base.is_resource_instance_root
1462        }
1463
1464        fn original_handle_in_resource(&self) -> Handle<Self> {
1465            self.base.original_handle_in_resource
1466        }
1467
1468        fn set_original_handle_in_resource(&mut self, handle: Handle<Self>) {
1469            self.base.original_handle_in_resource = handle;
1470        }
1471
1472        fn resource(&self) -> Option<Resource<Self::ResourceData>> {
1473            self.base.resource.clone()
1474        }
1475
1476        fn self_handle(&self) -> Handle<Self> {
1477            self.base.self_handle
1478        }
1479
1480        fn parent(&self) -> Handle<Self> {
1481            self.base.parent
1482        }
1483
1484        fn children(&self) -> &[Handle<Self>] {
1485            &self.base.children
1486        }
1487
1488        fn children_mut(&mut self) -> &mut [Handle<Self>] {
1489            &mut self.base.children
1490        }
1491    }
1492
1493    #[derive(Default, TypeUuidProvider, Visit, Reflect, Debug)]
1494    #[type_uuid(id = "fc887063-7780-44af-8710-5e0bcf9a83fd")]
1495    struct Graph {
1496        root: Handle<Node>,
1497        nodes: Pool<Node>,
1498    }
1499
1500    impl ResourceData for Graph {
1501        fn type_uuid(&self) -> Uuid {
1502            <Graph as TypeUuidProvider>::type_uuid()
1503        }
1504
1505        fn save(&mut self, _path: &Path) -> Result<(), Box<dyn Error>> {
1506            Ok(())
1507        }
1508
1509        fn can_be_saved(&self) -> bool {
1510            false
1511        }
1512    }
1513
1514    impl PrefabData for Graph {
1515        type Graph = Graph;
1516
1517        fn graph(&self) -> &Self::Graph {
1518            self
1519        }
1520
1521        fn mapping(&self) -> NodeMapping {
1522            NodeMapping::UseHandles
1523        }
1524    }
1525
1526    impl Index<Handle<Node>> for Graph {
1527        type Output = Node;
1528
1529        #[inline]
1530        fn index(&self, index: Handle<Node>) -> &Self::Output {
1531            &self.nodes[index]
1532        }
1533    }
1534
1535    impl IndexMut<Handle<Node>> for Graph {
1536        #[inline]
1537        fn index_mut(&mut self, index: Handle<Node>) -> &mut Self::Output {
1538            &mut self.nodes[index]
1539        }
1540    }
1541
1542    impl AbstractSceneGraph for Graph {
1543        fn try_get_node_untyped(&self, handle: ErasedHandle) -> Option<&dyn AbstractSceneNode> {
1544            self.nodes
1545                .try_borrow(handle.into())
1546                .map(|n| n as &dyn AbstractSceneNode)
1547        }
1548
1549        fn try_get_node_untyped_mut(
1550            &mut self,
1551            handle: ErasedHandle,
1552        ) -> Option<&mut dyn AbstractSceneNode> {
1553            self.nodes
1554                .try_borrow_mut(handle.into())
1555                .map(|n| n as &mut dyn AbstractSceneNode)
1556        }
1557    }
1558
1559    impl BaseSceneGraph for Graph {
1560        type Prefab = Graph;
1561        type Node = Node;
1562
1563        fn root(&self) -> Handle<Self::Node> {
1564            self.root
1565        }
1566
1567        fn set_root(&mut self, root: Handle<Self::Node>) {
1568            self.root = root;
1569        }
1570
1571        fn is_valid_handle(&self, handle: Handle<Self::Node>) -> bool {
1572            self.nodes.is_valid_handle(handle)
1573        }
1574
1575        fn add_node(&mut self, mut node: Self::Node) -> Handle<Self::Node> {
1576            let children = node.base.children.clone();
1577            node.base.children.clear();
1578            let handle = self.nodes.spawn(node);
1579
1580            if self.root.is_none() {
1581                self.root = handle;
1582            } else {
1583                self.link_nodes(handle, self.root);
1584            }
1585
1586            for child in children {
1587                self.link_nodes(child, handle);
1588            }
1589
1590            let node = &mut self.nodes[handle];
1591            node.base.self_handle = handle;
1592            handle
1593        }
1594
1595        fn remove_node(&mut self, node_handle: Handle<Self::Node>) {
1596            self.isolate_node(node_handle);
1597            let mut stack = vec![node_handle];
1598            while let Some(handle) = stack.pop() {
1599                stack.extend_from_slice(self.nodes[handle].children());
1600                self.nodes.free(handle);
1601            }
1602        }
1603
1604        fn link_nodes(&mut self, child: Handle<Self::Node>, parent: Handle<Self::Node>) {
1605            self.isolate_node(child);
1606            self.nodes[child].base.parent = parent;
1607            self.nodes[parent].base.children.push(child);
1608        }
1609
1610        fn unlink_node(&mut self, node_handle: Handle<Self::Node>) {
1611            self.isolate_node(node_handle);
1612            self.link_nodes(node_handle, self.root);
1613        }
1614
1615        fn isolate_node(&mut self, node_handle: Handle<Self::Node>) {
1616            let parent_handle =
1617                std::mem::replace(&mut self.nodes[node_handle].base.parent, Handle::NONE);
1618
1619            if let Some(parent) = self.nodes.try_borrow_mut(parent_handle) {
1620                if let Some(i) = parent.children().iter().position(|h| *h == node_handle) {
1621                    parent.base.children.remove(i);
1622                }
1623            }
1624        }
1625
1626        fn try_get(&self, handle: Handle<Self::Node>) -> Option<&Self::Node> {
1627            self.nodes.try_borrow(handle)
1628        }
1629
1630        fn try_get_mut(&mut self, handle: Handle<Self::Node>) -> Option<&mut Self::Node> {
1631            self.nodes.try_borrow_mut(handle)
1632        }
1633    }
1634
1635    impl SceneGraph for Graph {
1636        fn pair_iter(&self) -> impl Iterator<Item = (Handle<Self::Node>, &Self::Node)> {
1637            self.nodes.pair_iter()
1638        }
1639
1640        fn linear_iter(&self) -> impl Iterator<Item = &Self::Node> {
1641            self.nodes.iter()
1642        }
1643
1644        fn linear_iter_mut(&mut self) -> impl Iterator<Item = &mut Self::Node> {
1645            self.nodes.iter_mut()
1646        }
1647    }
1648
1649    #[test]
1650    fn test_set_child_position() {
1651        let mut graph = Graph::default();
1652
1653        let root = graph.add_node(Node::default());
1654        let a = graph.add_node(Node::default());
1655        let b = graph.add_node(Node::default());
1656        let c = graph.add_node(Node::default());
1657        let d = graph.add_node(Node::default());
1658        graph.link_nodes(a, root);
1659        graph.link_nodes(b, root);
1660        graph.link_nodes(c, root);
1661        graph.link_nodes(d, root);
1662
1663        let root_ref = &mut graph[root];
1664        assert_eq!(root_ref.set_child_position(a, 0), Some(0));
1665        assert_eq!(root_ref.set_child_position(b, 1), Some(1));
1666        assert_eq!(root_ref.set_child_position(c, 2), Some(2));
1667        assert_eq!(root_ref.set_child_position(d, 3), Some(3));
1668        assert_eq!(root_ref.children[0], a);
1669        assert_eq!(root_ref.children[1], b);
1670        assert_eq!(root_ref.children[2], c);
1671        assert_eq!(root_ref.children[3], d);
1672
1673        let initial_pos = root_ref.set_child_position(a, 3);
1674        assert_eq!(initial_pos, Some(0));
1675        assert_eq!(root_ref.children[0], b);
1676        assert_eq!(root_ref.children[1], c);
1677        assert_eq!(root_ref.children[2], d);
1678        assert_eq!(root_ref.children[3], a);
1679
1680        let prev_pos = root_ref.set_child_position(a, initial_pos.unwrap());
1681        assert_eq!(prev_pos, Some(3));
1682        assert_eq!(root_ref.children[0], a);
1683        assert_eq!(root_ref.children[1], b);
1684        assert_eq!(root_ref.children[2], c);
1685        assert_eq!(root_ref.children[3], d);
1686
1687        assert_eq!(root_ref.set_child_position(d, 1), Some(3));
1688        assert_eq!(root_ref.children[0], a);
1689        assert_eq!(root_ref.children[1], d);
1690        assert_eq!(root_ref.children[2], b);
1691        assert_eq!(root_ref.children[3], c);
1692
1693        assert_eq!(root_ref.set_child_position(d, 0), Some(1));
1694        assert_eq!(root_ref.children[0], d);
1695        assert_eq!(root_ref.children[1], a);
1696        assert_eq!(root_ref.children[2], b);
1697        assert_eq!(root_ref.children[3], c);
1698    }
1699
1700    #[test]
1701    fn test_change_root() {
1702        let mut graph = Graph::default();
1703
1704        // Root_
1705        //      |_A_
1706        //          |_B
1707        //          |_C_
1708        //             |_D
1709        let root = graph.add_node(Node {
1710            base: Base::default(),
1711        });
1712        let d = graph.add_node(Node {
1713            base: Base::default(),
1714        });
1715        let c = graph.add_node(Node {
1716            base: Base {
1717                children: vec![d],
1718                ..Default::default()
1719            },
1720        });
1721        let b = graph.add_node(Node {
1722            base: Base::default(),
1723        });
1724        let a = graph.add_node(Node {
1725            base: Base {
1726                children: vec![b, c],
1727                ..Default::default()
1728            },
1729        });
1730        graph.link_nodes(a, root);
1731
1732        dbg!(root, a, b, c, d);
1733
1734        let link_scheme = graph.change_hierarchy_root(root, c);
1735
1736        // C_
1737        //   |_D
1738        //   |_A_
1739        //       |_B
1740        //   |_Root
1741        assert_eq!(graph.root, c);
1742
1743        assert_eq!(graph[graph.root].parent, Handle::NONE);
1744        assert_eq!(graph[graph.root].children.len(), 3);
1745
1746        assert_eq!(graph[graph.root].children[0], d);
1747        assert_eq!(graph[d].parent, graph.root);
1748        assert!(graph[d].children.is_empty());
1749
1750        assert_eq!(graph[graph.root].children[1], a);
1751        assert_eq!(graph[a].parent, graph.root);
1752
1753        assert_eq!(graph[graph.root].children[2], root);
1754        assert_eq!(graph[root].parent, graph.root);
1755
1756        assert_eq!(graph[a].children.len(), 1);
1757        assert_eq!(graph[a].children[0], b);
1758        assert_eq!(graph[b].parent, a);
1759
1760        assert!(graph[b].children.is_empty());
1761
1762        // Revert
1763        graph.apply_link_scheme(link_scheme);
1764
1765        assert_eq!(graph.root, root);
1766        assert_eq!(graph[graph.root].parent, Handle::NONE);
1767        assert_eq!(graph[graph.root].children, vec![a]);
1768
1769        assert_eq!(graph[a].parent, root);
1770        assert_eq!(graph[a].children, vec![b, c]);
1771
1772        assert_eq!(graph[b].parent, a);
1773        assert_eq!(graph[b].children, vec![]);
1774
1775        assert_eq!(graph[c].parent, a);
1776        assert_eq!(graph[c].children, vec![d]);
1777    }
1778}