moonshine-object 0.3.1

Bevy Entities are nice. Objects are better!
Documentation
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
#![doc = include_str!("../README.md")]
#![warn(missing_docs)]

pub mod prelude {
    //! Prelude module to import all necessary traits and types for working with objects.

    pub use super::{GetObject, ObjectHierarchy, ObjectName, ObjectRebind, ObjectTags};
    pub use super::{Object, ObjectRef, ObjectWorldRef, Objects, RootObjects};
}

mod hierarchy;
mod name;
mod rebind;
mod tags;

use std::fmt;
use std::ops::Deref;

use bevy_ecs::entity::EntityNotSpawnedError;
use bevy_ecs::prelude::*;
use bevy_ecs::query::{QueryEntityError, QueryFilter, QuerySingleError};
use bevy_ecs::system::SystemParam;
use moonshine_kind::prelude::*;
use moonshine_util::hierarchy::HierarchyQuery;

pub use moonshine_kind::{Any, CastInto, Kind};
pub use moonshine_tag::{Tag, TagFilter, Tags};

pub use hierarchy::*;
pub use name::*;
pub use rebind::*;
pub use tags::*;

/// A [`SystemParam`] similar to [`Query`] which provides [`Object<T>`] access for its items.
#[derive(SystemParam)]
pub struct Objects<'w, 's, T = Any, F = ()>
where
    T: Kind,
    F: 'static + QueryFilter,
{
    /// [`Query`] used to filter instances of the given [`Kind`] `T`.
    pub instance: Query<'w, 's, Instance<T>, F>,
    /// [`HierarchyQuery`] used to traverse the object hierarchy.
    pub hierarchy: HierarchyQuery<'w, 's>,
    /// [`Query`] to identify objects by name or tags, mainly used for for hierarchy traversal and searching.
    pub nametags: Query<'w, 's, AnyOf<(&'static Name, &'static Tags)>>,
}

impl<'w, 's, T, F> Objects<'w, 's, T, F>
where
    T: Kind,
    F: 'static + QueryFilter,
{
    /// Iterates over all [`Object`]s of [`Kind`] `T` which match the [`QueryFilter`] `F`.
    pub fn iter(&self) -> impl Iterator<Item = Object<'w, 's, '_, T>> {
        self.instance.iter().map(|instance| Object {
            instance,
            hierarchy: &self.hierarchy,
            nametags: &self.nametags,
        })
    }

    /// Returns true if the given [`Entity`] is a valid [`Object<T>`].
    pub fn contains(&self, entity: Entity) -> bool {
        self.instance.contains(entity)
    }

    /// Returns an iterator over all [`ObjectRef`] instances of [`Kind`] `T` which match the [`QueryFilter`] `F`.
    pub fn iter_ref<'a>(
        &'a self,
        world: &'a World,
    ) -> impl Iterator<Item = ObjectRef<'w, 's, 'a, T>> {
        self.iter()
            .map(|object: Object<T>| ObjectRef(world.entity(object.entity()), object))
    }

    /// Returns an [`Object<T>`] from an [`Entity`], if it matches [`QueryFilter`] `F`.
    pub fn get(&self, entity: Entity) -> Result<Object<'w, 's, '_, T>, QueryEntityError> {
        self.instance.get(entity).map(|instance| Object {
            instance,
            hierarchy: &self.hierarchy,
            nametags: &self.nametags,
        })
    }

    /// Returns an [`ObjectRef<T>`] from an [`EntityRef`], if it matches [`QueryFilter`] `F`.
    pub fn get_ref<'a>(&'a self, entity: EntityRef<'a>) -> Option<ObjectRef<'w, 's, 'a, T>> {
        Some(ObjectRef(entity, self.get(entity.id()).ok()?))
    }

    /// Returns an [`Object<T>`], if it exists as a single instance.
    pub fn get_single(&self) -> Result<Object<'w, 's, '_, T>, QuerySingleError> {
        self.instance.single().map(|instance| Object {
            instance,
            hierarchy: &self.hierarchy,
            nametags: &self.nametags,
        })
    }

    /// Returns an [`ObjectRef<T>`] from an [`EntityRef`], if it exists as a single instance.
    pub fn get_single_ref<'a>(&'a self, entity: EntityRef<'a>) -> Option<ObjectRef<'w, 's, 'a, T>> {
        Some(ObjectRef(entity, self.get_single().ok()?))
    }

    /// Return an [`Object`] of [`Kind`] `T` from an [`Instance`].
    ///
    /// # Safety
    /// Assumes `instance` is a valid [`Instance`] of [`Kind`] `T`.
    pub fn instance(&self, instance: Instance<T>) -> Object<'w, 's, '_, T> {
        self.get(instance.entity()).expect("instance must be valid")
    }

    /// Return an [`Object`] of [`Kind`] `T` from an [`Instance`].
    pub fn get_instance(
        &self,
        instance: Instance<T>,
    ) -> Result<Object<'w, 's, '_, T>, QueryEntityError> {
        self.get(instance.entity())
    }
}

/// Ergonomic type alias for all [`Objects`] of [`Kind`] `T` without a parent.
pub type RootObjects<'w, 's, T = Any, F = ()> = Objects<'w, 's, T, (F, Without<ChildOf>)>;

/// Represents an [`Entity`] of [`Kind`] `T` with hierarchy and name information.
pub struct Object<'w, 's, 'a, T: Kind = Any> {
    instance: Instance<T>,
    hierarchy: &'a HierarchyQuery<'w, 's>,
    nametags: &'a Query<'w, 's, AnyOf<(&'static Name, &'static Tags)>>,
}

impl<'w, 's, 'a, T: Kind> Object<'w, 's, 'a, T> {
    /// Creates a new [`Object<T>`] from an [`Object<Any>`].
    ///
    /// This is semantically equivalent to an unsafe downcast.
    ///
    /// # Safety
    /// Assumes `base` is of [`Kind`] `T`.
    pub unsafe fn from_any_unchecked(object: Object<'w, 's, 'a>) -> Self {
        Self {
            instance: object.instance.cast_into_unchecked(),
            hierarchy: object.hierarchy,
            nametags: object.nametags,
        }
    }

    /// Returns the object as an [`Instance<T>`].
    pub fn instance(&self) -> Instance<T> {
        self.instance
    }

    /// Returns the object as an [`Entity`].
    pub fn entity(&self) -> Entity {
        self.instance.entity()
    }
}

impl<'w, 's, 'a, T: Component> Object<'w, 's, 'a, T> {
    /// Creates a new [`Object<T>`] from an [`Object<Any>`] if it is a valid instance of `T`.
    pub fn from_any(world: &World, object: Object<'w, 's, 'a>) -> Option<Object<'w, 's, 'a, T>> {
        let entity = world.entity(object.entity());
        let instance = Instance::<T>::from_entity(entity)?;
        // SAFE: Entity was just checked to a valid instance of T.
        Some(unsafe { object.rebind_as(instance) })
    }
}

impl<T: Kind> Clone for Object<'_, '_, '_, T> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<T: Kind> Copy for Object<'_, '_, '_, T> {}

impl<T: Kind> From<Object<'_, '_, '_, T>> for Entity {
    fn from(object: Object<'_, '_, '_, T>) -> Self {
        object.entity()
    }
}

impl<T: Kind> From<Object<'_, '_, '_, T>> for Instance<T> {
    fn from(object: Object<'_, '_, '_, T>) -> Self {
        object.instance()
    }
}

impl<T: Kind, U: Kind> PartialEq<Object<'_, '_, '_, U>> for Object<'_, '_, '_, T> {
    fn eq(&self, other: &Object<U>) -> bool {
        self.instance == other.instance
    }
}

impl<T: Kind> Eq for Object<'_, '_, '_, T> {}

impl<T: Kind> PartialEq<Instance<T>> for Object<'_, '_, '_, T> {
    fn eq(&self, other: &Instance<T>) -> bool {
        self.instance() == *other
    }
}

impl<T: Kind> PartialEq<Object<'_, '_, '_, T>> for Instance<T> {
    fn eq(&self, other: &Object<T>) -> bool {
        *self == other.instance()
    }
}

impl<T: Kind> PartialEq<Entity> for Object<'_, '_, '_, T> {
    fn eq(&self, other: &Entity) -> bool {
        self.entity() == *other
    }
}

impl<T: Kind> PartialEq<Object<'_, '_, '_, T>> for Entity {
    fn eq(&self, other: &Object<T>) -> bool {
        *self == other.entity()
    }
}

impl<T: Kind> fmt::Debug for Object<'_, '_, '_, T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(name) = self.name() {
            write!(f, "{}({:?}, \"{}\")", &T::debug_name(), self.entity(), name)
        } else {
            write!(f, "{}({:?})", &T::debug_name(), self.entity())
        }
    }
}

impl<T: Kind> fmt::Display for Object<'_, '_, '_, T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(name) = self.name() {
            write!(f, "{}({}, \"{}\")", &T::debug_name(), self.entity(), name)
        } else {
            write!(f, "{}({})", &T::debug_name(), self.entity())
        }
    }
}

impl<T: Kind> ContainsInstance<T> for Object<'_, '_, '_, T> {
    fn instance(&self) -> Instance<T> {
        self.instance
    }
}

/// Similar to [`EntityRef`] with the benefits of [`Object<T>`].
pub struct ObjectRef<'w, 's, 'a, T: Kind = Any>(EntityRef<'a>, Object<'w, 's, 'a, T>);

impl<'w, 's, 'a, T: Kind> ObjectRef<'w, 's, 'a, T> {
    /// Creates a new [`ObjectRef<T>`] from an [`ObjectRef<Any>`].
    ///
    /// This is semantically equivalent to an unsafe downcast.
    ///
    /// # Safety
    /// Assumes `base` is of [`Kind`] `T`.
    pub unsafe fn from_any_unchecked(base: ObjectRef<'w, 's, 'a>) -> Self {
        Self(base.0, Object::from_any_unchecked(base.1))
    }

    /// See [`EntityRef::get`].
    pub fn get<U: Component>(&self) -> Option<&U> {
        self.0.get::<U>()
    }

    /// See [`EntityRef::contains`].
    pub fn contains<U: Component>(&self) -> bool {
        self.0.contains::<U>()
    }

    /// Returns the object as an [`EntityRef`].
    pub fn as_entity(&self) -> EntityRef<'a> {
        self.0
    }
}

impl<T: Kind> Clone for ObjectRef<'_, '_, '_, T> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<T: Kind> Copy for ObjectRef<'_, '_, '_, T> {}

impl<T: Kind> From<ObjectRef<'_, '_, '_, T>> for Entity {
    fn from(object: ObjectRef<'_, '_, '_, T>) -> Self {
        object.entity()
    }
}

impl<T: Kind> From<ObjectRef<'_, '_, '_, T>> for Instance<T> {
    fn from(object: ObjectRef<'_, '_, '_, T>) -> Self {
        object.instance()
    }
}

impl<'w, 's, 'a, T: Kind> From<ObjectRef<'w, 's, 'a, T>> for Object<'w, 's, 'a, T> {
    fn from(object: ObjectRef<'w, 's, 'a, T>) -> Self {
        object.1
    }
}

impl<'w, 's, 'a, T: Kind> From<&ObjectRef<'w, 's, 'a, T>> for Object<'w, 's, 'a, T> {
    fn from(object: &ObjectRef<'w, 's, 'a, T>) -> Self {
        object.1
    }
}

impl<T: Kind> PartialEq for ObjectRef<'_, '_, '_, T> {
    fn eq(&self, other: &Self) -> bool {
        self.1 == other.1
    }
}

impl<T: Kind> Eq for ObjectRef<'_, '_, '_, T> {}

impl<T: Kind> ContainsInstance<T> for ObjectRef<'_, '_, '_, T> {
    fn instance(&self) -> Instance<T> {
        self.1.instance()
    }
}

impl<T: Component> Deref for ObjectRef<'_, '_, '_, T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        self.0.get::<T>().unwrap()
    }
}

impl<T: Kind> fmt::Debug for ObjectRef<'_, '_, '_, T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(name) = self.name() {
            write!(f, "{}({:?}, \"{}\")", &T::debug_name(), self.entity(), name)
        } else {
            write!(f, "{}({:?})", &T::debug_name(), self.entity())
        }
    }
}

impl<T: Kind> fmt::Display for ObjectRef<'_, '_, '_, T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(name) = self.name() {
            write!(f, "{}({}, \"{}\")", &T::debug_name(), self.entity(), name)
        } else {
            write!(f, "{}({})", &T::debug_name(), self.entity())
        }
    }
}

/// Similar to an [`ObjectRef`], but accessible via [`World`].
pub struct ObjectWorldRef<'w, T: Kind = Any> {
    instance: Instance<T>,
    world: &'w World,
}

impl<'w, T: Kind> ObjectWorldRef<'w, T> {
    /// Creates a new [`ObjectWorldRef<T>`] from an [`ObjectWorldRef<Any>`].
    ///
    /// This is semantically equivalent to an unsafe downcast.
    ///
    /// # Safety
    /// Assumes `object` is of [`Kind`] `T`.
    pub unsafe fn from_any_unchecked(object: ObjectWorldRef<'w>) -> Self {
        Self {
            instance: object.instance.cast_into_unchecked(),
            world: object.world,
        }
    }

    /// Creates a new [`ObjectWorldRef<T>`] from an [`ObjectWorldRef<Any>`] if the object
    /// contains the given [`Component`] `T`.
    ///
    /// This is semantically equivalent to a safe downcast.
    pub fn from_any(object: ObjectWorldRef<'w>) -> Option<Self>
    where
        T: Component,
    {
        Some(Self {
            instance: Instance::from_entity(object.as_entity())?,
            world: object.world,
        })
    }

    /// See [`EntityRef::get`].
    pub fn get<U: Component>(&self) -> Option<&U> {
        self.world.get::<U>(self.entity())
    }

    /// See [`EntityRef::contains`].
    pub fn contains<U: Component>(&self) -> bool {
        self.world.entity(self.entity()).contains::<U>()
    }

    /// Returns the object as an [`Instance<T>`].
    pub fn instance(&self) -> Instance<T> {
        self.instance
    }

    /// Returns the object as an [`Entity`].
    pub fn entity(&self) -> Entity {
        self.instance.entity()
    }

    /// Returns the object as an [`EntityRef`].
    pub fn as_entity(&self) -> EntityRef<'w> {
        self.world.entity(self.entity())
    }
}

impl<T: Kind> ContainsInstance<T> for ObjectWorldRef<'_, T> {
    fn instance(&self) -> Instance<T> {
        self.instance
    }
}

impl<T: Kind> Clone for ObjectWorldRef<'_, T> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<T: Kind> Copy for ObjectWorldRef<'_, T> {}

impl<T: Kind> From<ObjectWorldRef<'_, T>> for Entity {
    fn from(object: ObjectWorldRef<'_, T>) -> Self {
        object.entity()
    }
}

impl<T: Kind> From<ObjectWorldRef<'_, T>> for Instance<T> {
    fn from(object: ObjectWorldRef<'_, T>) -> Self {
        object.instance()
    }
}

impl<T: Kind, U: Kind> PartialEq<ObjectWorldRef<'_, U>> for ObjectWorldRef<'_, T> {
    fn eq(&self, other: &ObjectWorldRef<U>) -> bool {
        self.instance == other.instance
    }
}

impl<T: Kind> Eq for ObjectWorldRef<'_, T> {}

impl<T: Kind> PartialEq<Instance<T>> for ObjectWorldRef<'_, T> {
    fn eq(&self, other: &Instance<T>) -> bool {
        self.instance() == *other
    }
}

impl<T: Kind> PartialEq<ObjectWorldRef<'_, T>> for Instance<T> {
    fn eq(&self, other: &ObjectWorldRef<T>) -> bool {
        *self == other.instance()
    }
}

impl<T: Kind> PartialEq<Entity> for ObjectWorldRef<'_, T> {
    fn eq(&self, other: &Entity) -> bool {
        self.entity() == *other
    }
}

impl<T: Kind> PartialEq<ObjectWorldRef<'_, T>> for Entity {
    fn eq(&self, other: &ObjectWorldRef<T>) -> bool {
        *self == other.entity()
    }
}

impl<T: Kind> fmt::Debug for ObjectWorldRef<'_, T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(name) = self.name() {
            write!(f, "{}({:?}, \"{}\")", &T::debug_name(), self.entity(), name)
        } else {
            write!(f, "{}({:?})", &T::debug_name(), self.entity())
        }
    }
}

impl<T: Kind> fmt::Display for ObjectWorldRef<'_, T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(name) = self.name() {
            write!(f, "{}({}, \"{}\")", &T::debug_name(), self.entity(), name)
        } else {
            write!(f, "{}({})", &T::debug_name(), self.entity())
        }
    }
}

impl<T: Component> Deref for ObjectWorldRef<'_, T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        self.world.get::<T>(self.entity()).unwrap()
    }
}

/// Trait used to access an [`ObjectWorldRef`] from [`World`].
pub trait GetObject {
    /// Returns an [`ObjectWorldRef`] bounds to the given [`Entity`].
    ///
    /// # Safety
    ///
    /// This method will [`panic!`] if given entity is invalid.
    /// See [`get_object`](GetObject::get_object) for a safer alternative.
    fn object(&'_ self, entity: Entity) -> ObjectWorldRef<'_>;

    /// Returns an [`ObjectWorldRef`] bounds to the given [`Entity`], if it exists.
    fn get_object(&'_ self, entity: Entity) -> Result<ObjectWorldRef<'_>, EntityNotSpawnedError>;
}

impl GetObject for World {
    fn object(&'_ self, entity: Entity) -> ObjectWorldRef<'_> {
        ObjectWorldRef {
            instance: self.entity(entity).id().into(),
            world: self,
        }
    }

    fn get_object(&'_ self, entity: Entity) -> Result<ObjectWorldRef<'_>, EntityNotSpawnedError> {
        Ok(ObjectWorldRef {
            instance: self.get_entity(entity)?.id().into(),
            world: self,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    use bevy::ecs::system::RunSystemOnce;

    #[test]
    fn find_by_path() {
        let mut w = World::new();

        //     A
        //    /
        //   B
        //  / \
        // C   D

        let (a, b, c, d) = w
            .run_system_once(|mut commands: Commands| {
                let a = commands.spawn(Name::new("A")).id();
                let b = commands.spawn(Name::new("B")).id();
                let c = commands.spawn(Name::new("C")).id();
                let d = commands.spawn(Name::new("D")).id();

                commands.entity(a).add_children(&[b]);
                commands.entity(b).add_children(&[c, d]);

                (a, b, c, d)
            })
            .unwrap();

        w.run_system_once(move |objects: Objects| {
            let x = objects.get(a).unwrap().find_by_path("").unwrap();
            assert_eq!(a, x);
            assert_eq!(x.path(), "A");
        })
        .unwrap();

        w.run_system_once(move |objects: Objects| {
            let x = objects.get(a).unwrap().find_by_path(".").unwrap();
            assert_eq!(a, x);
            assert_eq!(x.path(), "A");
        })
        .unwrap();

        w.run_system_once(move |objects: Objects| {
            let x = objects.get(a).unwrap().find_by_path("B").unwrap();
            assert_eq!(b, x);
            assert_eq!(x.path(), "A/B");
        })
        .unwrap();

        w.run_system_once(move |objects: Objects| {
            let x = objects.get(a).unwrap().find_by_path("B/C").unwrap();
            assert_eq!(c, x);
            assert_eq!(x.path(), "A/B/C");
        })
        .unwrap();

        w.run_system_once(move |objects: Objects| {
            let x = objects.get(a).unwrap().find_by_path("B/D").unwrap();
            assert_eq!(d, x);
            assert_eq!(x.path(), "A/B/D");
        })
        .unwrap();

        w.run_system_once(move |objects: Objects| {
            let x = objects.get(a).unwrap().find_by_path("B/*").unwrap();
            assert_eq!(c, x);
            assert_eq!(x.path(), "A/B/C");
        })
        .unwrap();

        w.run_system_once(move |objects: Objects| {
            let x = objects.get(a).unwrap().find_by_path("*/D").unwrap();
            assert_eq!(d, x);
            assert_eq!(x.path(), "A/B/D");
        })
        .unwrap();

        w.run_system_once(move |objects: Objects| {
            let x = objects.get(a).unwrap().find_by_path("*/*").unwrap();
            assert_eq!(c, x);
            assert_eq!(x.path(), "A/B/C");
        })
        .unwrap();

        w.run_system_once(move |objects: Objects| {
            let x = objects.get(b).unwrap().find_by_path("..").unwrap();
            assert_eq!(a, x);
            assert_eq!(x.path(), "A");
        })
        .unwrap();

        w.run_system_once(move |objects: Objects| {
            let x = objects.get(c).unwrap().find_by_path("..").unwrap();
            assert_eq!(b, x);
            assert_eq!(x.path(), "A/B");
        })
        .unwrap();

        w.run_system_once(move |objects: Objects| {
            let x = objects.get(c).unwrap().find_by_path("../D").unwrap();
            assert_eq!(d, x);
            assert_eq!(x.path(), "A/B/D");
        })
        .unwrap();

        w.run_system_once(move |objects: Objects| {
            let x = objects.get(c).unwrap().find_by_path("../C").unwrap();
            assert_eq!(c, x);
            assert_eq!(x.path(), "A/B/C");
        })
        .unwrap();
    }

    #[test]
    fn object_ref() {
        #[derive(Component)]
        struct T;

        let mut w = World::new();
        let entity = w.spawn(T).id();

        assert!(w
            .run_system_once(move |world: &World, objects: Objects<T>| {
                objects
                    .get_single_ref(world.entity(entity))
                    .unwrap()
                    .contains::<T>()
            })
            .unwrap());
    }

    #[test]
    fn world_object_ref() {
        #[derive(Component)]
        struct T;

        let mut w = World::new();
        let entity = w.spawn(T).id();

        let object = ObjectWorldRef::<T>::from_any(w.object(entity)).unwrap();

        assert_eq!(object, entity);
    }

    #[test]
    fn root_objects() {
        #[derive(Component)]
        struct T;

        //     A
        //    /
        //   B
        //  / \
        // C   D

        let mut w = World::new();
        let root = w
            .spawn(T) /* A */
            .with_children(|children| {
                children.spawn(T /* B */).with_children(|children| {
                    children.spawn(T /* C */);
                    children.spawn(T /* D */);
                });
            })
            .id();

        assert!(w
            .run_system_once(move |objects: RootObjects<T>| {
                assert_eq!(objects.iter().count(), 1);
                assert!(objects.contains(root));
                assert!(objects.get_single().is_ok());
                true
            })
            .unwrap());
    }
}