bevy_defer 0.17.0

A simple asynchronous runtime for executing async coroutines.
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
use crate::access::AsyncWorld;
use crate::executor::{with_world_mut, with_world_ref};
use crate::signals::Observed;
use crate::InspectEntity;
use crate::OwnedReadonlyQueryState;
use crate::{access::AsyncEntityMut, AccessError, AccessResult};
use bevy::ecs::bundle::BundleFromComponents;
use bevy::ecs::component::Component;
use bevy::ecs::event::EntityEvent;
use bevy::ecs::hierarchy::{ChildOf, Children};
use bevy::ecs::name::Name;
use bevy::ecs::observer::On;
use bevy::ecs::relationship::{Relationship, RelationshipTarget};
use bevy::ecs::system::{EntityCommand, IntoObserverSystem};
use bevy::ecs::world::{EntityRef, EntityWorldMut};
use bevy::ecs::{bundle::Bundle, entity::Entity, world::World};
use bevy::transform::components::{GlobalTransform, Transform};
use event_listener::Event as AsyncEvent;
use futures::channel::mpsc;
use futures::future::Either;
use futures::Stream;
use rustc_hash::FxHashMap;
use std::any::type_name;
use std::borrow::Borrow;
use std::future::{ready, Future};

impl AsyncEntityMut {
    /// Run a function on the [`EntityRef`].
    ///
    /// Can be used inside a readonly world access scope and
    /// converts the scope into a readonly world access scope.
    ///
    /// # Example
    ///
    /// ```
    /// # bevy_defer::test_spawn!({
    /// # let entity1 = AsyncWorld.spawn_bundle(Int(1));
    /// # let entity2 = AsyncWorld.spawn_bundle(Int(2));
    /// // creates a readonly world access scope
    /// entity1.get(|a| {
    ///     dbg!(a.id());
    ///     // can be used in a readonly world access scope
    ///     entity2.get(|b| {
    ///         dbg!(b.id());
    ///     })
    /// })
    /// # });
    /// ```
    pub fn get<T>(&self, f: impl FnOnce(EntityRef) -> T) -> AccessResult<T> {
        let entity = self.0;
        with_world_ref(|w| {
            if let Ok(e) = w.get_entity(entity) {
                Ok(f(e))
            } else {
                Err(AccessError::EntityNotFound(entity))
            }
        })
    }

    /// Run a function on the [`EntityWorldMut`].
    pub fn get_mut<T>(&self, f: impl FnOnce(EntityWorldMut) -> T) -> AccessResult<T> {
        let entity = self.0;
        with_world_mut(|w| {
            if let Ok(e) = w.get_entity_mut(entity) {
                Ok(f(e))
            } else {
                Err(AccessError::EntityNotFound(entity))
            }
        })
    }

    /// Apply an [`EntityCommand`].
    pub fn apply_command(&self, command: impl EntityCommand) -> AccessResult<AsyncEntityMut> {
        let entity = self.0;
        with_world_mut(|w| {
            if let Ok(e) = w.get_entity_mut(entity) {
                command.apply(e);
                Ok(AsyncEntityMut(entity))
            } else {
                Err(AccessError::EntityNotFound(entity))
            }
        })
    }

    /// Check if an [`Entity`] exists.
    pub fn exists(&self) -> bool {
        let entity = self.0;
        with_world_mut(move |world: &mut World| world.get_entity(entity).is_ok())
    }

    /// Adds a [`Bundle`] of components to the entity.
    ///
    /// # Example
    ///
    /// ```
    /// # bevy_defer::test_spawn!({
    /// # let entity = AsyncWorld.spawn_bundle(Int(1));
    /// entity.insert(Str("bevy"));
    /// # });
    /// ```
    pub fn insert(&self, bundle: impl Bundle) -> Result<Self, AccessError> {
        let entity = self.0;
        with_world_mut(move |world: &mut World| {
            world
                .get_entity_mut(entity)
                .map(|mut e| {
                    e.insert(bundle);
                })
                .map_err(|_| AccessError::EntityNotFound(entity))
        })?;
        Ok(AsyncEntityMut(entity))
    }

    /// Removes any components in the [`Bundle`] from the entity.
    ///
    /// # Example
    ///
    /// ```
    /// # bevy_defer::test_spawn!({
    /// # let entity = AsyncWorld.spawn_bundle(Int(1));
    /// entity.remove::<Int>();
    /// # });
    /// ```
    pub fn remove<T: Bundle>(&self) -> Result<Self, AccessError> {
        let entity = self.0;
        with_world_mut(move |world: &mut World| {
            world
                .get_entity_mut(entity)
                .map(|mut e| {
                    e.remove::<T>();
                })
                .map_err(|_| AccessError::EntityNotFound(entity))
        })?;
        Ok(AsyncEntityMut(entity))
    }

    /// Removes any components except those in the [`Bundle`] from the entity.
    ///
    /// # Example
    ///
    /// ```
    /// # bevy_defer::test_spawn!({
    /// # let entity = AsyncWorld.spawn_bundle(Int(1));
    /// entity.retain::<Int>();
    /// # });
    /// ```
    pub fn retain<T: Bundle>(&self) -> Result<Self, AccessError> {
        let entity = self.0;
        with_world_mut(move |world: &mut World| {
            world
                .get_entity_mut(entity)
                .map(|mut e| {
                    e.retain::<T>();
                })
                .map_err(|_| AccessError::EntityNotFound(entity))
        })?;
        Ok(AsyncEntityMut(entity))
    }

    /// Removes all components in the [`Bundle`] from the entity and returns their previous values.
    ///
    /// Note: If the entity does not have every component in the bundle, this method will not remove any of them.
    ///
    /// # Example
    ///
    /// ```
    /// # bevy_defer::test_spawn!({
    /// # let entity = AsyncWorld.spawn_bundle(Int(1));
    /// entity.take::<Int>();
    /// # });
    /// ```
    pub fn take<T: Bundle + BundleFromComponents>(&self) -> Result<T, AccessError> {
        let entity = self.0;
        with_world_mut(move |world: &mut World| {
            world
                .get_entity_mut(entity)
                .map_err(|_| AccessError::EntityNotFound(entity))
                .and_then(|mut e| {
                    e.take::<T>().ok_or(AccessError::ComponentNotFound {
                        name: type_name::<T>(),
                    })
                })
        })
    }

    /// Creates an `Observer` listening for events of type `E` targeting this entity.
    ///
    /// In order to trigger the callback the entity must also match the query when the event is fired.
    pub fn observe<E: EntityEvent, B: Bundle, M>(
        &self,
        observer: impl IntoObserverSystem<E, B, M>,
    ) -> AccessResult {
        let entity = self.0;
        with_world_mut(move |world: &mut World| {
            world
                .get_entity_mut(entity)
                .map_err(|_| AccessError::EntityNotFound(entity))?
                .observe(observer);
            Ok(())
        })
    }

    /// Triggers the given event for this entity, which will run any observers watching for it.
    pub fn trigger<E: EntityEvent>(&self, event: impl FnOnce(Entity) -> E) -> AccessResult
    where
        for<'t> E::Trigger<'t>: Default,
    {
        let entity = self.0;
        with_world_mut(move |world: &mut World| {
            world
                .get_entity_mut(entity)
                .map_err(|_| AccessError::EntityNotFound(entity))?
                .trigger(event);
            Ok(())
        })
    }

    /// Spawns an entity with the given bundle and inserts it into the parent entity's Children.
    ///
    /// # Example
    ///
    /// ```
    /// # bevy_defer::test_spawn!({
    /// # let entity = AsyncWorld.spawn_bundle(Int(1));
    /// let child = entity.spawn_child(Str("bevy"));
    /// # });
    /// ```
    pub fn spawn_child(&self, bundle: impl Bundle) -> AccessResult<AsyncEntityMut> {
        let entity = self.0;
        let entity = with_world_mut(move |world: &mut World| {
            world
                .get_entity_mut(entity)
                .map(|mut entity| {
                    let mut id = Entity::PLACEHOLDER;
                    entity.with_children(|spawn| id = spawn.spawn(bundle).id());
                    id
                })
                .map_err(|_| AccessError::EntityNotFound(entity))
        })?;
        Ok(AsyncWorld.entity(entity))
    }

    /// Spawns an entity with the given bundle and inserts it into the parent entity's Children.
    ///
    /// # Example
    ///
    /// ```
    /// # bevy_defer::test_spawn!({
    /// # let entity = AsyncWorld.spawn_bundle(Int(1));
    /// let child = entity.spawn_related::<ChildOf>(Str("bevy"));
    /// # });
    /// ```
    pub fn spawn_related<R: Relationship>(
        &self,
        bundle: impl Bundle,
    ) -> AccessResult<AsyncEntityMut> {
        let entity = self.0;
        let entity = with_world_mut(move |world: &mut World| {
            world
                .get_entity_mut(entity)
                .map(|mut entity| {
                    let mut id = Entity::PLACEHOLDER;
                    entity.with_related_entities::<R>(|spawn| id = spawn.spawn(bundle).id());
                    id
                })
                .map_err(|_| AccessError::EntityNotFound(entity))
        })?;
        Ok(AsyncWorld.entity(entity))
    }

    /// Adds a single child, returns the parent [`AsyncEntityMut`].
    ///
    /// # Example
    ///
    /// ```
    /// # bevy_defer::test_spawn!({
    /// # let entity = AsyncWorld.spawn_bundle(Int(1));
    /// # let child = AsyncWorld.spawn_bundle(Int(1)).id();
    /// entity.add_child(child);
    /// # });
    /// ```
    pub fn add_child(&self, child: Entity) -> AccessResult<AsyncEntityMut> {
        let entity = self.0;
        with_world_mut(move |world: &mut World| {
            world
                .get_entity_mut(entity)
                .map(|mut entity| {
                    entity.add_child(child);
                })
                .map_err(|_| AccessError::EntityNotFound(entity))
        })?;
        Ok(AsyncEntityMut(entity))
    }

    /// Adds a single child, returns the parent [`AsyncEntityMut`].
    ///
    /// # Example
    ///
    /// ```
    /// # bevy_defer::test_spawn!({
    /// # let entity = AsyncWorld.spawn_bundle(Int(1));
    /// # let child = AsyncWorld.spawn_bundle(Int(1)).id();
    /// entity.add_child(child);
    /// # });
    /// ```
    pub fn add_related<R: Relationship>(&self, child: Entity) -> AccessResult<AsyncEntityMut> {
        let entity = self.0;
        with_world_mut(move |world: &mut World| {
            world
                .get_entity_mut(entity)
                .map(|mut entity| {
                    entity.add_related::<R>(&[child]);
                })
                .map_err(|_| AccessError::EntityNotFound(entity))
        })?;
        Ok(AsyncEntityMut(entity))
    }

    /// Obtain parent of an entity.
    ///
    /// # Example
    ///
    /// ```
    /// # bevy_defer::test_spawn!({
    /// # let entity = AsyncWorld.spawn_bundle(Int(1));
    /// # let child = entity.spawn_child(Int(1)).unwrap();
    /// child.parent()
    /// # ;
    /// # assert_eq!(child.parent().unwrap().id(), entity.id());
    /// # });
    /// ```
    pub fn parent(&self) -> AccessResult<AsyncEntityMut> {
        let entity = self.0;
        let child = with_world_mut(move |world: &mut World| {
            world
                .get_entity(entity)
                .ok()
                .and_then(|entity| entity.get::<ChildOf>().map(|x| x.parent()))
                .ok_or(AccessError::EntityNotFound(entity))
        })?;
        Ok(AsyncEntityMut(child))
    }

    /// Set parent to an entity.
    ///
    /// # Example
    ///
    /// ```
    /// # bevy_defer::test_spawn!({
    /// # let entity = AsyncWorld.spawn_bundle(Int(1));
    /// # let child = AsyncWorld.spawn_bundle(Int(1)).id();
    /// entity.set_parent(child);
    /// # });
    /// ```
    pub fn set_parent(&self, parent: impl Borrow<Entity>) -> AccessResult<AsyncEntityMut> {
        let entity = self.0;
        with_world_mut(move |world: &mut World| {
            world
                .get_entity_mut(entity)
                .map(|mut entity| {
                    entity.insert(ChildOf(*parent.borrow()));
                })
                .map_err(|_| AccessError::EntityNotFound(entity))
        })?;
        Ok(AsyncEntityMut(entity))
    }

    /// Create a [`Stream`] of a specific triggered event.
    ///
    /// `T` corresponds to `Trigger<T>` in observers.
    ///
    /// # Note
    ///
    /// This function spawns an observer.
    pub fn on<T: EntityEvent + Clone>(&self) -> AccessResult<impl Stream<Item = T> + 'static> {
        let entity = self.id();
        let (sender, receiver) = mpsc::unbounded();
        with_world_mut(|world| {
            world
                .get_entity_mut(entity)
                .map(|mut entity| {
                    entity.observe(move |trigger: On<T>| {
                        let _ = sender.unbounded_send(trigger.event().clone());
                    });
                })
                .map_err(|_| AccessError::EntityNotFound(entity))
        })?;
        Ok(receiver)
    }

    /// Initialize a signal receiver [`Observed<T>`] on this entity
    /// and spawn an observer that feeds into that signal receiver.
    ///
    /// Call [`AsyncEntityMut::signal_receiver`] to read from that signal.
    pub fn signal_observe<T: EntityEvent + Clone>(&self) -> AccessResult {
        let entity = self.id();
        let signal = self.signal_receiver::<Observed<T>>()?;
        with_world_mut(|world| {
            world.entity_mut(entity).observe(move |trigger: On<T>| {
                signal.write(trigger.event().clone());
            });
        });
        Ok(())
    }

    /// Returns a future that yields when the entity is despawned.
    pub fn on_despawn(&self) -> impl Future + use<> + 'static {
        #[derive(Component)]
        struct OnDespawn(AsyncEvent);

        impl Drop for OnDespawn {
            fn drop(&mut self) {
                self.0.notify(usize::MAX);
            }
        }
        let entity = self.0;

        with_world_mut(|w| {
            let Ok(mut entity) = w.get_entity_mut(entity) else {
                return Either::Left(ready(()));
            };
            if let Some(event) = entity.get::<OnDespawn>() {
                Either::Right(event.0.listen())
            } else {
                let on_despawn = OnDespawn(AsyncEvent::new());
                let event = on_despawn.0.listen();
                entity.insert(on_despawn);
                Either::Right(event)
            }
        })
    }

    /// Despawns the given entity and all its children recursively.
    ///
    /// # Example
    ///
    /// ```
    /// # bevy_defer::test_spawn!({
    /// # let entity = AsyncWorld.spawn_bundle(Int(1));
    /// entity.despawn();
    /// # });
    /// ```
    pub fn despawn(&self) {
        let entity = self.0;
        with_world_mut(move |world: &mut World| {
            world.despawn(entity);
        })
    }

    /// Despawns the given entity's children recursively.
    ///
    /// # Example
    ///
    /// ```
    /// # bevy_defer::test_spawn!({
    /// # let entity = AsyncWorld.spawn_bundle(Int(1));
    /// entity.despawn_related::<Children>();
    /// # });
    /// ```
    pub fn despawn_related<R: RelationshipTarget>(&self) {
        let entity = self.0;
        with_world_mut(move |world: &mut World| {
            if let Ok(mut entity) = world.get_entity_mut(entity) {
                entity.despawn_related::<R>();
            }
        })
    }

    /// Get [`Name`] of the entity.
    pub fn name(&self) -> AccessResult<String> {
        self.component::<Name>().get(|x| x.to_string())
    }

    /// Get [`Name`] and index of the entity.
    pub fn debug_string(&self) -> String {
        InspectEntity(self.0).to_string()
    }

    /// Obtain all descendent entities in the hierarchy.
    ///
    /// # Guarantee
    ///
    /// The first item is always this entity,
    /// use `[1..]` to exclude it.
    pub fn descendants(&self) -> Vec<Entity> {
        fn get_children(world: &World, parent: Entity, result: &mut Vec<Entity>) {
            let Ok(entity) = world.get_entity(parent) else {
                return;
            };
            if let Some(children) = entity.get::<Children>() {
                result.extend(children.iter());
                for child in children {
                    get_children(world, *child, result);
                }
            }
        }
        let entity = self.0;

        let mut result = vec![entity];

        with_world_ref(|world| get_children(world, entity, &mut result));
        result
    }

    /// Returns a string containing the names of component types on this entity.
    ///
    /// If the entity is missing, returns an error message.
    pub fn debug_print(&self) -> String {
        let e = self.id();
        with_world_ref(|w| {
            if let Ok(i) = w.inspect_entity(e) {
                let v: Vec<_> = i.map(|x| x.name().shortname().to_string()).collect();
                v.join(", ")
            } else {
                format!("Entity {e} missing!")
            }
        })
    }

    /// Obtain a child entity by index.
    pub fn child(&self, index: usize) -> AccessResult<AsyncEntityMut> {
        match self.component::<Children>().get(|x| x.get(index).copied()) {
            Ok(Some(entity)) => Ok(self.world().entity(entity)),
            _ => Err(AccessError::ChildNotFound { index }),
        }
    }

    /// Collect [`Children`] into a [`Vec`].
    pub fn children_vec(&self) -> Vec<Entity> {
        let entity = self.0;
        with_world_ref(|world| {
            world
                .entity(entity)
                .get::<Children>()
                .map(|x| x.iter().collect())
                .unwrap_or_default()
        })
    }

    /// Obtain a child entity by [`Name`].
    pub fn child_by_name(
        &self,
        name: impl Into<String> + Borrow<str>,
    ) -> AccessResult<AsyncEntityMut> {
        fn find_name(world: &World, parent: Entity, name: &str) -> Option<Entity> {
            let entity = world.get_entity(parent).ok()?;
            if entity.get::<Name>().map(|x| x.as_str() == name) == Some(true) {
                return Some(parent);
            }
            if let Some(children) = entity.get::<Children>() {
                let children: Vec<_> = children.iter().collect();
                children.into_iter().find_map(|e| find_name(world, e, name))
            } else {
                None
            }
        }
        let entity = self.0;

        match with_world_ref(|world| find_name(world, entity, name.borrow())) {
            Some(entity) => Ok(AsyncEntityMut(entity)),
            None => Err(AccessError::EntityNotFound(entity)),
        }
    }

    /// Obtain a child entity by [`Name`].
    pub fn children_by_names<I: IntoIterator>(&self, names: I) -> NameEntityMap
    where
        I::Item: Into<String>,
    {
        let descendants = self.descendants();
        let mut result = NameEntityMap(names.into_iter().map(|n| (n.into(), None)).collect());
        with_world_ref(|world| {
            let mut query_state = OwnedReadonlyQueryState::<(Entity, &Name), ()>::new(world);
            for (entity, name) in query_state.iter_many(descendants) {
                if let Some(item) = result.0.get_mut(name.as_str()) {
                    *item = Some(entity);
                }
            }
        });
        result
    }

    /// Obtain an entity's real [`GlobalTransform`] by traversing its ancestors,
    /// this is a relatively slow operation compared to reading [`GlobalTransform`] directly.
    ///
    /// # Errors
    ///
    /// If [`Entity`] or [`Transform`] is missing in one of the target's ancestors.
    pub fn global_transform(&self) -> AccessResult<GlobalTransform> {
        with_world_ref(|world| {
            let mut entity = world.get_entity(self.0).ok()?;
            let mut transform = *entity.get::<Transform>()?;
            while let Some(parent) = entity.get::<ChildOf>().map(|x| x.parent()) {
                entity = world.get_entity(parent).ok()?;
                transform = entity.get::<Transform>()?.mul_transform(transform)
            }
            Some(transform.into())
        })
        .ok_or(AccessError::ComponentNotFound {
            name: type_name::<GlobalTransform>(),
        })
    }

    /// Obtain an entity's real visibility by traversing its ancestors.
    ///
    /// # Errors
    ///
    /// If `Visibility` is missing in one of the target's ancestors.
    #[cfg(feature = "bevy_render")]
    pub fn visibility(&self) -> AccessResult<bool> {
        use bevy::prelude::Visibility;
        with_world_ref(|world| {
            let entity = world.get_entity(self.0).ok()?;
            match entity.get::<Visibility>()? {
                Visibility::Inherited => (),
                Visibility::Hidden => return Some(false),
                Visibility::Visible => return Some(true),
            }
            while let Some(parent) = entity.get::<ChildOf>().map(|x| x.parent()) {
                match world.get_entity(parent).ok()?.get::<Visibility>()? {
                    Visibility::Inherited => (),
                    Visibility::Hidden => return Some(false),
                    Visibility::Visible => return Some(true),
                }
            }
            Some(true)
        })
        .ok_or(AccessError::ComponentNotFound {
            name: type_name::<Visibility>(),
        })
    }
}

/// A map of names to entities.
#[derive(Debug, Default, Clone)]
pub struct NameEntityMap(FxHashMap<String, Option<Entity>>);

impl NameEntityMap {
    pub fn get(&self, name: impl Borrow<str>) -> AccessResult<Entity> {
        self.0
            .get(name.borrow())
            .copied()
            .flatten()
            .ok_or(AccessError::Custom("named entity missing"))
    }

    pub fn into_map(self) -> impl IntoIterator<Item = (String, Entity)> {
        self.0.into_iter().filter_map(|(s, e)| Some((s, e?)))
    }
}