bevy_ecs/
hierarchy.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
//! The canonical "parent-child" [`Relationship`] for entities, driven by
//! the [`ChildOf`] [`Relationship`] and the [`Children`] [`RelationshipTarget`].
//!
//! See [`ChildOf`] for a full description of the relationship and how to use it.
//!
//! [`Relationship`]: crate::relationship::Relationship
//! [`RelationshipTarget`]: crate::relationship::RelationshipTarget

#[cfg(feature = "bevy_reflect")]
use crate::reflect::{ReflectComponent, ReflectFromWorld};
use crate::{
    bundle::Bundle,
    component::{Component, HookContext},
    entity::Entity,
    relationship::{RelatedSpawner, RelatedSpawnerCommands},
    system::EntityCommands,
    world::{DeferredWorld, EntityWorldMut, FromWorld, World},
};
use alloc::{format, string::String, vec::Vec};
#[cfg(feature = "bevy_reflect")]
use bevy_reflect::std_traits::ReflectDefault;
use core::ops::Deref;
use core::slice;
use disqualified::ShortName;
use log::warn;

/// Stores the parent entity of this child entity with this component.
///
/// This is a [`Relationship`] component, and creates the canonical
/// "parent / child" hierarchy. This is the "source of truth" component, and it pairs with
/// the [`Children`] [`RelationshipTarget`](crate::relationship::RelationshipTarget).
///
/// This relationship should be used for things like:
///
/// 1. Organizing entities in a scene
/// 2. Propagating configuration or data inherited from a parent, such as "visibility" or "world-space global transforms".
/// 3. Ensuring a hierarchy is despawned when an entity is despawned.
///
/// [`ChildOf`] contains a single "target" [`Entity`]. When [`ChildOf`] is inserted on a "source" entity,
/// the "target" entity will automatically (and immediately, via a component hook) have a [`Children`]
/// component inserted, and the "source" entity will be added to that [`Children`] instance.
///
/// If the [`ChildOf`] component is replaced with a different "target" entity, the old target's [`Children`]
/// will be automatically (and immediately, via a component hook) be updated to reflect that change.
///
/// Likewise, when the [`ChildOf`] component is removed, the "source" entity will be removed from the old
/// target's [`Children`]. If this results in [`Children`] being empty, [`Children`] will be automatically removed.
///
/// When a parent is despawned, all children (and their descendants) will _also_ be despawned.
///
/// You can create parent-child relationships in a variety of ways. The most direct way is to insert a [`ChildOf`] component:
///
/// ```
/// # use bevy_ecs::prelude::*;
/// # let mut world = World::new();
/// let root = world.spawn_empty().id();
/// let child1 = world.spawn(ChildOf(root)).id();
/// let child2 = world.spawn(ChildOf(root)).id();
/// let grandchild = world.spawn(ChildOf(child1)).id();
///
/// assert_eq!(&**world.entity(root).get::<Children>().unwrap(), &[child1, child2]);
/// assert_eq!(&**world.entity(child1).get::<Children>().unwrap(), &[grandchild]);
///
/// world.entity_mut(child2).remove::<ChildOf>();
/// assert_eq!(&**world.entity(root).get::<Children>().unwrap(), &[child1]);
///
/// world.entity_mut(root).despawn();
/// assert!(world.get_entity(root).is_err());
/// assert!(world.get_entity(child1).is_err());
/// assert!(world.get_entity(grandchild).is_err());
/// ```
///
/// However if you are spawning many children, you might want to use the [`EntityWorldMut::with_children`] helper instead:
///
/// ```
/// # use bevy_ecs::prelude::*;
/// # let mut world = World::new();
/// let mut child1 = Entity::PLACEHOLDER;
/// let mut child2 = Entity::PLACEHOLDER;
/// let mut grandchild = Entity::PLACEHOLDER;
/// let root = world.spawn_empty().with_children(|p| {
///     child1 = p.spawn_empty().with_children(|p| {
///         grandchild = p.spawn_empty().id();
///     }).id();
///     child2 = p.spawn_empty().id();
/// }).id();
///
/// assert_eq!(&**world.entity(root).get::<Children>().unwrap(), &[child1, child2]);
/// assert_eq!(&**world.entity(child1).get::<Children>().unwrap(), &[grandchild]);
/// ```
///
/// [`Relationship`]: crate::relationship::Relationship
#[derive(Component, Clone, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "bevy_reflect", derive(bevy_reflect::Reflect))]
#[cfg_attr(
    feature = "bevy_reflect",
    reflect(Component, PartialEq, Debug, FromWorld, Clone)
)]
#[relationship(relationship_target = Children)]
#[doc(alias = "IsChild", alias = "Parent")]
pub struct ChildOf(pub Entity);

impl ChildOf {
    /// The parent entity of this child entity.
    #[inline]
    pub fn parent(&self) -> Entity {
        self.0
    }

    /// The parent entity of this child entity.
    #[deprecated(since = "0.16.0", note = "Use child_of.parent() instead")]
    #[inline]
    pub fn get(&self) -> Entity {
        self.0
    }
}

// TODO: We need to impl either FromWorld or Default so ChildOf can be registered as Reflect.
// This is because Reflect deserialize by creating an instance and apply a patch on top.
// However ChildOf should only ever be set with a real user-defined entity.  Its worth looking into
// better ways to handle cases like this.
impl FromWorld for ChildOf {
    #[inline(always)]
    fn from_world(_world: &mut World) -> Self {
        ChildOf(Entity::PLACEHOLDER)
    }
}

/// Tracks which entities are children of this parent entity.
///
/// A [`RelationshipTarget`] collection component that is populated
/// with entities that "target" this entity with the [`ChildOf`] [`Relationship`] component.
///
/// Together, these components form the "canonical parent-child hierarchy". See the [`ChildOf`] component for the full
/// description of this relationship and instructions on how to use it.
///
/// # Usage
///
/// Like all [`RelationshipTarget`] components, this data should not be directly manipulated to avoid desynchronization.
/// Instead, modify the [`ChildOf`] components on the "source" entities.
///
/// To access the children of an entity, you can iterate over the [`Children`] component,
/// using the [`IntoIterator`] trait.
/// For more complex access patterns, see the [`RelationshipTarget`] trait.
///
/// [`Relationship`]: crate::relationship::Relationship
/// [`RelationshipTarget`]: crate::relationship::RelationshipTarget
#[derive(Component, Default, Debug, PartialEq, Eq)]
#[relationship_target(relationship = ChildOf, linked_spawn)]
#[cfg_attr(feature = "bevy_reflect", derive(bevy_reflect::Reflect))]
#[cfg_attr(feature = "bevy_reflect", reflect(Component, FromWorld, Default))]
#[doc(alias = "IsParent")]
pub struct Children(Vec<Entity>);

impl Children {
    /// Swaps the child at `a_index` with the child at `b_index`.
    #[inline]
    pub fn swap(&mut self, a_index: usize, b_index: usize) {
        self.0.swap(a_index, b_index);
    }

    /// Sorts children [stably](https://en.wikipedia.org/wiki/Sorting_algorithm#Stability)
    /// in place using the provided comparator function.
    ///
    /// For the underlying implementation, see [`slice::sort_by`].
    ///
    /// For the unstable version, see [`sort_unstable_by`](Children::sort_unstable_by).
    ///
    /// See also [`sort_by_key`](Children::sort_by_key), [`sort_by_cached_key`](Children::sort_by_cached_key).
    #[inline]
    pub fn sort_by<F>(&mut self, compare: F)
    where
        F: FnMut(&Entity, &Entity) -> core::cmp::Ordering,
    {
        self.0.sort_by(compare);
    }

    /// Sorts children [stably](https://en.wikipedia.org/wiki/Sorting_algorithm#Stability)
    /// in place using the provided key extraction function.
    ///
    /// For the underlying implementation, see [`slice::sort_by_key`].
    ///
    /// For the unstable version, see [`sort_unstable_by_key`](Children::sort_unstable_by_key).
    ///
    /// See also [`sort_by`](Children::sort_by), [`sort_by_cached_key`](Children::sort_by_cached_key).
    #[inline]
    pub fn sort_by_key<K, F>(&mut self, compare: F)
    where
        F: FnMut(&Entity) -> K,
        K: Ord,
    {
        self.0.sort_by_key(compare);
    }

    /// Sorts children [stably](https://en.wikipedia.org/wiki/Sorting_algorithm#Stability)
    /// in place using the provided key extraction function. Only evaluates each key at most
    /// once per sort, caching the intermediate results in memory.
    ///
    /// For the underlying implementation, see [`slice::sort_by_cached_key`].
    ///
    /// See also [`sort_by`](Children::sort_by), [`sort_by_key`](Children::sort_by_key).
    #[inline]
    pub fn sort_by_cached_key<K, F>(&mut self, compare: F)
    where
        F: FnMut(&Entity) -> K,
        K: Ord,
    {
        self.0.sort_by_cached_key(compare);
    }

    /// Sorts children [unstably](https://en.wikipedia.org/wiki/Sorting_algorithm#Stability)
    /// in place using the provided comparator function.
    ///
    /// For the underlying implementation, see [`slice::sort_unstable_by`].
    ///
    /// For the stable version, see [`sort_by`](Children::sort_by).
    ///
    /// See also [`sort_unstable_by_key`](Children::sort_unstable_by_key).
    #[inline]
    pub fn sort_unstable_by<F>(&mut self, compare: F)
    where
        F: FnMut(&Entity, &Entity) -> core::cmp::Ordering,
    {
        self.0.sort_unstable_by(compare);
    }

    /// Sorts children [unstably](https://en.wikipedia.org/wiki/Sorting_algorithm#Stability)
    /// in place using the provided key extraction function.
    ///
    /// For the underlying implementation, see [`slice::sort_unstable_by_key`].
    ///
    /// For the stable version, see [`sort_by_key`](Children::sort_by_key).
    ///
    /// See also [`sort_unstable_by`](Children::sort_unstable_by).
    #[inline]
    pub fn sort_unstable_by_key<K, F>(&mut self, compare: F)
    where
        F: FnMut(&Entity) -> K,
        K: Ord,
    {
        self.0.sort_unstable_by_key(compare);
    }
}

impl<'a> IntoIterator for &'a Children {
    type Item = <Self::IntoIter as Iterator>::Item;

    type IntoIter = slice::Iter<'a, Entity>;

    #[inline(always)]
    fn into_iter(self) -> Self::IntoIter {
        self.0.iter()
    }
}

impl Deref for Children {
    type Target = [Entity];

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

/// A type alias over [`RelatedSpawner`] used to spawn child entities containing a [`ChildOf`] relationship.
pub type ChildSpawner<'w> = RelatedSpawner<'w, ChildOf>;

/// A type alias over [`RelatedSpawnerCommands`] used to spawn child entities containing a [`ChildOf`] relationship.
pub type ChildSpawnerCommands<'w> = RelatedSpawnerCommands<'w, ChildOf>;

impl<'w> EntityWorldMut<'w> {
    /// Spawns children of this entity (with a [`ChildOf`] relationship) by taking a function that operates on a [`ChildSpawner`].
    /// See also [`with_related`](Self::with_related).
    pub fn with_children(&mut self, func: impl FnOnce(&mut ChildSpawner)) -> &mut Self {
        self.with_related_entities(func);
        self
    }

    /// Adds the given children to this entity
    /// See also [`add_related`](Self::add_related).
    pub fn add_children(&mut self, children: &[Entity]) -> &mut Self {
        self.add_related::<ChildOf>(children)
    }

    /// Insert children at specific index.
    /// See also [`insert_related`](Self::insert_related).
    pub fn insert_children(&mut self, index: usize, children: &[Entity]) -> &mut Self {
        self.insert_related::<ChildOf>(index, children)
    }

    /// Adds the given child to this entity
    /// See also [`add_related`](Self::add_related).
    pub fn add_child(&mut self, child: Entity) -> &mut Self {
        self.add_related::<ChildOf>(&[child])
    }

    /// Removes the relationship between this entity and the given entities.
    pub fn remove_children(&mut self, children: &[Entity]) -> &mut Self {
        self.remove_related::<ChildOf>(children)
    }

    /// Replaces all the related children with a new set of children.
    pub fn replace_children(&mut self, children: &[Entity]) -> &mut Self {
        self.replace_related::<ChildOf>(children)
    }

    /// Replaces all the related children with a new set of children.
    ///
    /// # Warning
    ///
    /// Failing to maintain the functions invariants may lead to erratic engine behavior including random crashes.
    /// Refer to [`Self::replace_related_with_difference`] for a list of these invariants.
    ///
    /// # Panics
    ///
    /// Panics when debug assertions are enabled if an invariant is is broken and the command is executed.
    pub fn replace_children_with_difference(
        &mut self,
        entities_to_unrelate: &[Entity],
        entities_to_relate: &[Entity],
        newly_related_entities: &[Entity],
    ) -> &mut Self {
        self.replace_related_with_difference::<ChildOf>(
            entities_to_unrelate,
            entities_to_relate,
            newly_related_entities,
        )
    }

    /// Spawns the passed bundle and adds it to this entity as a child.
    ///
    /// For efficient spawning of multiple children, use [`with_children`].
    ///
    /// [`with_children`]: EntityWorldMut::with_children
    pub fn with_child(&mut self, bundle: impl Bundle) -> &mut Self {
        let parent = self.id();
        self.world_scope(|world| {
            world.spawn((bundle, ChildOf(parent)));
        });
        self
    }

    /// Removes the [`ChildOf`] component, if it exists.
    #[deprecated(since = "0.16.0", note = "Use entity_mut.remove::<ChildOf>()")]
    pub fn remove_parent(&mut self) -> &mut Self {
        self.remove::<ChildOf>();
        self
    }

    /// Inserts the [`ChildOf`] component with the given `parent` entity, if it exists.
    #[deprecated(since = "0.16.0", note = "Use entity_mut.insert(ChildOf(entity))")]
    pub fn set_parent(&mut self, parent: Entity) -> &mut Self {
        self.insert(ChildOf(parent));
        self
    }
}

impl<'a> EntityCommands<'a> {
    /// Spawns children of this entity (with a [`ChildOf`] relationship) by taking a function that operates on a [`ChildSpawner`].
    pub fn with_children(
        &mut self,
        func: impl FnOnce(&mut RelatedSpawnerCommands<ChildOf>),
    ) -> &mut Self {
        self.with_related_entities(func);
        self
    }

    /// Adds the given children to this entity
    pub fn add_children(&mut self, children: &[Entity]) -> &mut Self {
        self.add_related::<ChildOf>(children)
    }

    /// Insert children at specific index.
    /// See also [`insert_related`](Self::insert_related).
    pub fn insert_children(&mut self, index: usize, children: &[Entity]) -> &mut Self {
        self.insert_related::<ChildOf>(index, children)
    }

    /// Adds the given child to this entity
    pub fn add_child(&mut self, child: Entity) -> &mut Self {
        self.add_related::<ChildOf>(&[child])
    }

    /// Removes the relationship between this entity and the given entities.
    pub fn remove_children(&mut self, children: &[Entity]) -> &mut Self {
        self.remove_related::<ChildOf>(children)
    }

    /// Replaces the children on this entity with a new list of children.
    pub fn replace_children(&mut self, children: &[Entity]) -> &mut Self {
        self.replace_related::<ChildOf>(children)
    }

    /// Replaces all the related entities with a new set of entities.
    ///
    /// # Warning
    ///
    /// Failing to maintain the functions invariants may lead to erratic engine behavior including random crashes.
    /// Refer to [`EntityWorldMut::replace_related_with_difference`] for a list of these invariants.
    ///
    /// # Panics
    ///
    /// Panics when debug assertions are enabled if an invariant is is broken and the command is executed.
    pub fn replace_children_with_difference(
        &mut self,
        entities_to_unrelate: &[Entity],
        entities_to_relate: &[Entity],
        newly_related_entities: &[Entity],
    ) -> &mut Self {
        self.replace_related_with_difference::<ChildOf>(
            entities_to_unrelate,
            entities_to_relate,
            newly_related_entities,
        )
    }

    /// Spawns the passed bundle and adds it to this entity as a child.
    ///
    /// For efficient spawning of multiple children, use [`with_children`].
    ///
    /// [`with_children`]: EntityCommands::with_children
    pub fn with_child(&mut self, bundle: impl Bundle) -> &mut Self {
        self.with_related::<ChildOf>(bundle);
        self
    }

    /// Removes the [`ChildOf`] component, if it exists.
    #[deprecated(since = "0.16.0", note = "Use entity_commands.remove::<ChildOf>()")]
    pub fn remove_parent(&mut self) -> &mut Self {
        self.remove::<ChildOf>();
        self
    }

    /// Inserts the [`ChildOf`] component with the given `parent` entity, if it exists.
    #[deprecated(since = "0.16.0", note = "Use entity_commands.insert(ChildOf(entity))")]
    pub fn set_parent(&mut self, parent: Entity) -> &mut Self {
        self.insert(ChildOf(parent));
        self
    }
}

/// An `on_insert` component hook that when run, will validate that the parent of a given entity
/// contains component `C`. This will print a warning if the parent does not contain `C`.
pub fn validate_parent_has_component<C: Component>(
    world: DeferredWorld,
    HookContext { entity, caller, .. }: HookContext,
) {
    let entity_ref = world.entity(entity);
    let Some(child_of) = entity_ref.get::<ChildOf>() else {
        return;
    };
    if !world
        .get_entity(child_of.parent())
        .is_ok_and(|e| e.contains::<C>())
    {
        // TODO: print name here once Name lives in bevy_ecs
        let name: Option<String> = None;
        warn!(
            "warning[B0004]: {}{name} with the {ty_name} component has a parent without {ty_name}.\n\
            This will cause inconsistent behaviors! See: https://bevyengine.org/learn/errors/b0004",
            caller.map(|c| format!("{c}: ")).unwrap_or_default(),
            ty_name = ShortName::of::<C>(),
            name = name.map_or_else(
                || format!("Entity {}", entity),
                |s| format!("The {s} entity")
            ),
        );
    }
}

/// Returns a [`SpawnRelatedBundle`] that will insert the [`Children`] component, spawn a [`SpawnableList`] of entities with given bundles that
/// relate to the [`Children`] entity via the [`ChildOf`] component, and reserve space in the [`Children`] for each spawned entity.
///
/// Any additional arguments will be interpreted as bundles to be spawned.
///
/// Also see [`related`](crate::related) for a version of this that works with any [`RelationshipTarget`] type.
///
/// ```
/// # use bevy_ecs::hierarchy::Children;
/// # use bevy_ecs::name::Name;
/// # use bevy_ecs::world::World;
/// # use bevy_ecs::children;
/// # use bevy_ecs::spawn::{Spawn, SpawnRelated};
/// let mut world = World::new();
/// world.spawn((
///     Name::new("Root"),
///     children![
///         Name::new("Child1"),
///         (
///             Name::new("Child2"),
///             children![Name::new("Grandchild")]
///         )
///     ]
/// ));
/// ```
///
/// [`RelationshipTarget`]: crate::relationship::RelationshipTarget
/// [`SpawnRelatedBundle`]: crate::spawn::SpawnRelatedBundle
/// [`SpawnableList`]: crate::spawn::SpawnableList
#[macro_export]
macro_rules! children {
    [$($child:expr),*$(,)?] => {
       $crate::hierarchy::Children::spawn(($($crate::spawn::Spawn($child)),*))
    };
}

#[cfg(test)]
mod tests {
    use crate::{
        entity::Entity,
        hierarchy::{ChildOf, Children},
        relationship::{RelationshipHookMode, RelationshipTarget},
        spawn::{Spawn, SpawnRelated},
        world::World,
    };
    use alloc::{vec, vec::Vec};

    #[derive(PartialEq, Eq, Debug)]
    struct Node {
        entity: Entity,
        children: Vec<Node>,
    }

    impl Node {
        fn new(entity: Entity) -> Self {
            Self {
                entity,
                children: Vec::new(),
            }
        }

        fn new_with(entity: Entity, children: Vec<Node>) -> Self {
            Self { entity, children }
        }
    }

    fn get_hierarchy(world: &World, entity: Entity) -> Node {
        Node {
            entity,
            children: world
                .entity(entity)
                .get::<Children>()
                .map_or_else(Default::default, |c| {
                    c.iter().map(|e| get_hierarchy(world, e)).collect()
                }),
        }
    }

    #[test]
    fn hierarchy() {
        let mut world = World::new();
        let root = world.spawn_empty().id();
        let child1 = world.spawn(ChildOf(root)).id();
        let grandchild = world.spawn(ChildOf(child1)).id();
        let child2 = world.spawn(ChildOf(root)).id();

        // Spawn
        let hierarchy = get_hierarchy(&world, root);
        assert_eq!(
            hierarchy,
            Node::new_with(
                root,
                vec![
                    Node::new_with(child1, vec![Node::new(grandchild)]),
                    Node::new(child2)
                ]
            )
        );

        // Removal
        world.entity_mut(child1).remove::<ChildOf>();
        let hierarchy = get_hierarchy(&world, root);
        assert_eq!(hierarchy, Node::new_with(root, vec![Node::new(child2)]));

        // Insert
        world.entity_mut(child1).insert(ChildOf(root));
        let hierarchy = get_hierarchy(&world, root);
        assert_eq!(
            hierarchy,
            Node::new_with(
                root,
                vec![
                    Node::new(child2),
                    Node::new_with(child1, vec![Node::new(grandchild)])
                ]
            )
        );

        // Recursive Despawn
        world.entity_mut(root).despawn();
        assert!(world.get_entity(root).is_err());
        assert!(world.get_entity(child1).is_err());
        assert!(world.get_entity(child2).is_err());
        assert!(world.get_entity(grandchild).is_err());
    }

    #[test]
    fn with_children() {
        let mut world = World::new();
        let mut child1 = Entity::PLACEHOLDER;
        let mut child2 = Entity::PLACEHOLDER;
        let root = world
            .spawn_empty()
            .with_children(|p| {
                child1 = p.spawn_empty().id();
                child2 = p.spawn_empty().id();
            })
            .id();

        let hierarchy = get_hierarchy(&world, root);
        assert_eq!(
            hierarchy,
            Node::new_with(root, vec![Node::new(child1), Node::new(child2)])
        );
    }

    #[test]
    fn add_children() {
        let mut world = World::new();
        let child1 = world.spawn_empty().id();
        let child2 = world.spawn_empty().id();
        let root = world.spawn_empty().add_children(&[child1, child2]).id();

        let hierarchy = get_hierarchy(&world, root);
        assert_eq!(
            hierarchy,
            Node::new_with(root, vec![Node::new(child1), Node::new(child2)])
        );
    }

    #[test]
    fn insert_children() {
        let mut world = World::new();
        let child1 = world.spawn_empty().id();
        let child2 = world.spawn_empty().id();
        let child3 = world.spawn_empty().id();
        let child4 = world.spawn_empty().id();

        let mut entity_world_mut = world.spawn_empty();

        let first_children = entity_world_mut.add_children(&[child1, child2]);

        let root = first_children.insert_children(1, &[child3, child4]).id();

        let hierarchy = get_hierarchy(&world, root);
        assert_eq!(
            hierarchy,
            Node::new_with(
                root,
                vec![
                    Node::new(child1),
                    Node::new(child3),
                    Node::new(child4),
                    Node::new(child2)
                ]
            )
        );
    }

    #[test]
    fn remove_children() {
        let mut world = World::new();
        let child1 = world.spawn_empty().id();
        let child2 = world.spawn_empty().id();
        let child3 = world.spawn_empty().id();
        let child4 = world.spawn_empty().id();

        let mut root = world.spawn_empty();
        root.add_children(&[child1, child2, child3, child4]);
        root.remove_children(&[child2, child3]);
        let root = root.id();

        let hierarchy = get_hierarchy(&world, root);
        assert_eq!(
            hierarchy,
            Node::new_with(root, vec![Node::new(child1), Node::new(child4)])
        );
    }

    #[test]
    fn self_parenting_invalid() {
        let mut world = World::new();
        let id = world.spawn_empty().id();
        world.entity_mut(id).insert(ChildOf(id));
        assert!(
            world.entity(id).get::<ChildOf>().is_none(),
            "invalid ChildOf relationships should self-remove"
        );
    }

    #[test]
    fn missing_parent_invalid() {
        let mut world = World::new();
        let parent = world.spawn_empty().id();
        world.entity_mut(parent).despawn();
        let id = world.spawn(ChildOf(parent)).id();
        assert!(
            world.entity(id).get::<ChildOf>().is_none(),
            "invalid ChildOf relationships should self-remove"
        );
    }

    #[test]
    fn reinsert_same_parent() {
        let mut world = World::new();
        let parent = world.spawn_empty().id();
        let id = world.spawn(ChildOf(parent)).id();
        world.entity_mut(id).insert(ChildOf(parent));
        assert_eq!(
            Some(&ChildOf(parent)),
            world.entity(id).get::<ChildOf>(),
            "ChildOf should still be there"
        );
    }

    #[test]
    fn spawn_children() {
        let mut world = World::new();
        let id = world.spawn(Children::spawn((Spawn(()), Spawn(())))).id();
        assert_eq!(world.entity(id).get::<Children>().unwrap().len(), 2,);
    }

    #[test]
    fn replace_children() {
        let mut world = World::new();
        let parent = world.spawn(Children::spawn((Spawn(()), Spawn(())))).id();
        let &[child_a, child_b] = &world.entity(parent).get::<Children>().unwrap().0[..] else {
            panic!("Tried to spawn 2 children on an entity and didn't get 2 children");
        };

        let child_c = world.spawn_empty().id();

        world
            .entity_mut(parent)
            .replace_children(&[child_a, child_c]);

        let children = world.entity(parent).get::<Children>().unwrap();

        assert!(children.contains(&child_a));
        assert!(children.contains(&child_c));
        assert!(!children.contains(&child_b));

        assert_eq!(
            world.entity(child_a).get::<ChildOf>().unwrap(),
            &ChildOf(parent)
        );
        assert_eq!(
            world.entity(child_c).get::<ChildOf>().unwrap(),
            &ChildOf(parent)
        );
        assert!(world.entity(child_b).get::<ChildOf>().is_none());
    }

    #[test]
    fn replace_children_with_nothing() {
        let mut world = World::new();
        let parent = world.spawn_empty().id();
        let child_a = world.spawn_empty().id();
        let child_b = world.spawn_empty().id();

        world.entity_mut(parent).add_children(&[child_a, child_b]);

        assert_eq!(world.entity(parent).get::<Children>().unwrap().len(), 2);

        world.entity_mut(parent).replace_children(&[]);

        assert!(world.entity(child_a).get::<ChildOf>().is_none());
        assert!(world.entity(child_b).get::<ChildOf>().is_none());
    }

    #[test]
    fn insert_same_child_twice() {
        let mut world = World::new();

        let parent = world.spawn_empty().id();
        let child = world.spawn_empty().id();

        world.entity_mut(parent).add_child(child);
        world.entity_mut(parent).add_child(child);

        let children = world.get::<Children>(parent).unwrap();
        assert_eq!(children.0, [child]);
        assert_eq!(
            world.entity(child).get::<ChildOf>().unwrap(),
            &ChildOf(parent)
        );
    }

    #[test]
    fn replace_with_difference() {
        let mut world = World::new();

        let parent = world.spawn_empty().id();
        let child_a = world.spawn_empty().id();
        let child_b = world.spawn_empty().id();
        let child_c = world.spawn_empty().id();
        let child_d = world.spawn_empty().id();

        // Test inserting new relations
        world.entity_mut(parent).replace_children_with_difference(
            &[],
            &[child_a, child_b],
            &[child_a, child_b],
        );

        assert_eq!(
            world.entity(child_a).get::<ChildOf>().unwrap(),
            &ChildOf(parent)
        );
        assert_eq!(
            world.entity(child_b).get::<ChildOf>().unwrap(),
            &ChildOf(parent)
        );
        assert_eq!(
            world.entity(parent).get::<Children>().unwrap().0,
            [child_a, child_b]
        );

        // Test replacing relations and changing order
        world.entity_mut(parent).replace_children_with_difference(
            &[child_b],
            &[child_d, child_c, child_a],
            &[child_c, child_d],
        );
        assert_eq!(
            world.entity(child_a).get::<ChildOf>().unwrap(),
            &ChildOf(parent)
        );
        assert_eq!(
            world.entity(child_c).get::<ChildOf>().unwrap(),
            &ChildOf(parent)
        );
        assert_eq!(
            world.entity(child_d).get::<ChildOf>().unwrap(),
            &ChildOf(parent)
        );
        assert_eq!(
            world.entity(parent).get::<Children>().unwrap().0,
            [child_d, child_c, child_a]
        );
        assert!(!world.entity(child_b).contains::<ChildOf>());

        // Test removing relationships
        world.entity_mut(parent).replace_children_with_difference(
            &[child_a, child_d, child_c],
            &[],
            &[],
        );
        assert!(!world.entity(parent).contains::<Children>());
        assert!(!world.entity(child_a).contains::<ChildOf>());
        assert!(!world.entity(child_b).contains::<ChildOf>());
        assert!(!world.entity(child_c).contains::<ChildOf>());
        assert!(!world.entity(child_d).contains::<ChildOf>());
    }

    #[test]
    fn replace_with_difference_on_empty() {
        let mut world = World::new();

        let parent = world.spawn_empty().id();
        let child_a = world.spawn_empty().id();

        world
            .entity_mut(parent)
            .replace_children_with_difference(&[child_a], &[], &[]);

        assert!(!world.entity(parent).contains::<Children>());
        assert!(!world.entity(child_a).contains::<ChildOf>());
    }

    #[test]
    fn replace_with_difference_totally_new_children() {
        let mut world = World::new();

        let parent = world.spawn_empty().id();
        let child_a = world.spawn_empty().id();
        let child_b = world.spawn_empty().id();
        let child_c = world.spawn_empty().id();
        let child_d = world.spawn_empty().id();

        // Test inserting new relations
        world.entity_mut(parent).replace_children_with_difference(
            &[],
            &[child_a, child_b],
            &[child_a, child_b],
        );

        assert_eq!(
            world.entity(child_a).get::<ChildOf>().unwrap(),
            &ChildOf(parent)
        );
        assert_eq!(
            world.entity(child_b).get::<ChildOf>().unwrap(),
            &ChildOf(parent)
        );
        assert_eq!(
            world.entity(parent).get::<Children>().unwrap().0,
            [child_a, child_b]
        );

        // Test replacing relations and changing order
        world.entity_mut(parent).replace_children_with_difference(
            &[child_b, child_a],
            &[child_d, child_c],
            &[child_c, child_d],
        );
        assert_eq!(
            world.entity(child_c).get::<ChildOf>().unwrap(),
            &ChildOf(parent)
        );
        assert_eq!(
            world.entity(child_d).get::<ChildOf>().unwrap(),
            &ChildOf(parent)
        );
        assert_eq!(
            world.entity(parent).get::<Children>().unwrap().0,
            [child_d, child_c]
        );
        assert!(!world.entity(child_a).contains::<ChildOf>());
        assert!(!world.entity(child_b).contains::<ChildOf>());
    }

    #[test]
    fn replace_children_order() {
        let mut world = World::new();

        let parent = world.spawn_empty().id();
        let child_a = world.spawn_empty().id();
        let child_b = world.spawn_empty().id();
        let child_c = world.spawn_empty().id();
        let child_d = world.spawn_empty().id();

        let initial_order = [child_a, child_b, child_c, child_d];
        world.entity_mut(parent).add_children(&initial_order);

        assert_eq!(
            world.entity_mut(parent).get::<Children>().unwrap().0,
            initial_order
        );

        let new_order = [child_d, child_b, child_a, child_c];
        world.entity_mut(parent).replace_children(&new_order);

        assert_eq!(world.entity(parent).get::<Children>().unwrap().0, new_order);
    }

    #[test]
    #[should_panic]
    #[cfg_attr(
        not(debug_assertions),
        ignore = "we don't check invariants if debug assertions are off"
    )]
    fn replace_diff_invariant_overlapping_unrelate_with_relate() {
        let mut world = World::new();

        let parent = world.spawn_empty().id();
        let child_a = world.spawn_empty().id();

        world
            .entity_mut(parent)
            .replace_children_with_difference(&[], &[child_a], &[child_a]);

        // This should panic
        world
            .entity_mut(parent)
            .replace_children_with_difference(&[child_a], &[child_a], &[]);
    }

    #[test]
    #[should_panic]
    #[cfg_attr(
        not(debug_assertions),
        ignore = "we don't check invariants if debug assertions are off"
    )]
    fn replace_diff_invariant_overlapping_unrelate_with_newly() {
        let mut world = World::new();

        let parent = world.spawn_empty().id();
        let child_a = world.spawn_empty().id();
        let child_b = world.spawn_empty().id();

        world
            .entity_mut(parent)
            .replace_children_with_difference(&[], &[child_a], &[child_a]);

        // This should panic
        world.entity_mut(parent).replace_children_with_difference(
            &[child_b],
            &[child_a, child_b],
            &[child_b],
        );
    }

    #[test]
    #[should_panic]
    #[cfg_attr(
        not(debug_assertions),
        ignore = "we don't check invariants if debug assertions are off"
    )]
    fn replace_diff_invariant_newly_not_subset() {
        let mut world = World::new();

        let parent = world.spawn_empty().id();
        let child_a = world.spawn_empty().id();
        let child_b = world.spawn_empty().id();

        // This should panic
        world.entity_mut(parent).replace_children_with_difference(
            &[],
            &[child_a, child_b],
            &[child_a],
        );
    }

    #[test]
    fn child_replace_hook_skip() {
        let mut world = World::new();
        let parent = world.spawn_empty().id();
        let other = world.spawn_empty().id();
        let child = world.spawn(ChildOf(parent)).id();
        world
            .entity_mut(child)
            .insert_with_relationship_hook_mode(ChildOf(other), RelationshipHookMode::Skip);
        assert_eq!(
            &**world.entity(parent).get::<Children>().unwrap(),
            &[child],
            "Children should still have the old value, as on_insert/on_replace didn't run"
        );
    }
}