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
use crate::access::AsyncResource;
use crate::channel;
use crate::executor::{with_world_mut, with_world_ref, QUERY_QUEUE, REACTORS, WORLD};
use crate::sync::oneshot::{ChannelOut, MaybeChannelOut};
use crate::{access::AsyncEntityMut, reactors::StateSignal, signals::SignalId, tween::AsSeconds};
use crate::{access::AsyncWorld, AccessError, AccessResult};
use async_shared::Value;
use bevy::app::AppExit;
use bevy::ecs::event::Event;
use bevy::ecs::message::{Message, MessageId};
use bevy::ecs::system::{Command, IntoSystem, SystemId};
use bevy::ecs::world::{CommandQueue, FromWorld, Mut};
use bevy::ecs::{bundle::Bundle, resource::Resource, schedule::ScheduleLabel, world::World};
use bevy::prelude::SystemInput;
use bevy::state::state::{FreelyMutableState, NextState, State, States};
use bevy::tasks::AsyncComputeTaskPool;
use futures::future::ready;
use futures::future::Either;
use futures::stream::FusedStream;
use std::any::type_name;
use std::task::Context;
use std::time::Duration;
use std::{
    future::{poll_fn, Future},
    task::Poll,
};

#[allow(unused)]
use bevy::ecs::entity::Entity;

impl AsyncWorld {
    /// Apply a command.
    ///
    /// Use [`AsyncWorld::run`] to obtain a result instead.
    ///
    /// # Example
    ///
    /// ```
    /// # bevy_defer::test_spawn!(
    /// AsyncWorld.apply_command(|w: &mut World| println!("{:?}", w))
    /// # );
    /// ```
    pub fn apply_command(&self, command: impl Command) {
        with_world_mut(|w| command.apply(w))
    }

    /// Apply a [`CommandQueue`].
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy::ecs::world::CommandQueue;
    /// # bevy_defer::test_spawn!({
    /// let queue = CommandQueue::default();
    /// AsyncWorld.apply_command_queue(queue);
    /// # });
    /// ```
    pub fn apply_command_queue(&self, mut commands: CommandQueue) {
        with_world_mut(|w| commands.apply(w))
    }

    /// Apply a function on the [`World`] and obtain the result.
    ///
    /// # Example
    ///
    /// ```
    /// # bevy_defer::test_spawn!(
    /// AsyncWorld.run(|w: &mut World| w.resource::<Int>().0)
    /// # );
    /// ```
    pub fn run<T>(&self, f: impl FnOnce(&mut World) -> T) -> T {
        with_world_mut(f)
    }

    /// Apply a readonly function on the [`World`] and obtain the result.
    ///
    /// Can be used inside a readonly world access scope and
    /// converts the scope into a readonly world access scope.
    ///
    /// # Example
    ///
    /// ```
    /// # bevy_defer::test_spawn!(
    /// // creates a readonly world access scope
    /// AsyncWorld.read(|w: &World|
    ///     // can be used inside a world access scope
    ///     AsyncWorld.read(|w: &World|
    ///         w.resource::<Int>().0
    ///     )
    /// )
    /// # );
    /// ```
    pub fn read<T>(&self, f: impl FnOnce(&World) -> T) -> T {
        with_world_ref(f)
    }

    /// Apply a function on the [`World`], repeat until it returns `Some`.
    ///
    /// ## Note
    ///
    /// Dropping the future will stop the task.
    ///
    /// # Example
    ///
    /// ```
    /// # bevy_defer::test_spawn!(
    /// AsyncWorld.watch(|w: &mut World| w.get_resource::<Int>().map(|r| r.0)).await
    /// # );
    /// ```
    pub fn watch<T: 'static>(
        &self,
        f: impl FnMut(&mut World) -> Option<T> + 'static,
    ) -> ChannelOut<T> {
        let (sender, receiver) = channel();
        QUERY_QUEUE.with(|queue| queue.repeat(f, sender));
        receiver.into_out()
    }

    /// Watch as [`Either::Left`].
    pub(crate) fn watch_left<T: 'static, R: Future>(
        &self,
        f: impl FnMut(&mut World) -> Option<T> + 'static,
    ) -> Either<ChannelOut<T>, R> {
        let (sender, receiver) = channel();
        QUERY_QUEUE.with(|queue| queue.repeat(f, sender));
        Either::Left(receiver.into_out())
    }

    /// Runs a schedule a single time.
    ///
    /// # Example
    ///
    /// ```
    /// # bevy_defer::test_spawn!(
    /// AsyncWorld.run_schedule(Update)
    /// # );
    /// ```
    pub fn run_schedule(&self, schedule: impl ScheduleLabel) -> AccessResult {
        with_world_mut(move |world: &mut World| {
            world
                .try_run_schedule(schedule)
                .map_err(|_| AccessError::ScheduleNotFound)
        })
    }

    /// Obtain a [`Resource`] in a scoped function.
    /// [`AsyncWorld`] can be used inside as this is not considered an access function.
    ///
    /// # Example
    ///
    /// ```
    /// # bevy_defer::test_spawn!(
    /// AsyncWorld.run(|w: &mut World| w.resource::<Int>().0)
    /// # );
    /// ```
    pub fn resource_scope<R: Resource, T>(&self, f: impl FnOnce(Mut<R>) -> T) -> T {
        with_world_mut(|w| w.resource_scope(|w, r| WORLD.set(w, || f(r))))
    }

    /// Register a system and return a [`SystemId`] so it can later be called by `run_system`.
    ///
    /// # Example
    ///
    /// ```
    /// # bevy_defer::test_spawn!(
    /// AsyncWorld.register_system(|time: Res<Time>| println!("{}", time.delta_secs()))
    /// # );
    /// ```
    pub fn register_system<
        I: SystemInput + 'static,
        O: 'static,
        M,
        S: IntoSystem<I, O, M> + 'static,
    >(
        &self,
        system: S,
    ) -> SystemId<I, O> {
        with_world_mut(move |world: &mut World| world.register_system(system))
    }

    /// Run a stored system by their [`SystemId`].
    ///
    /// # Example
    ///
    /// ```
    /// # bevy_defer::test_spawn!({
    /// let id = AsyncWorld.register_system(|time: Res<Time>| println!("{}", time.delta_secs()));
    /// AsyncWorld.run_system(id).unwrap();
    /// # });
    /// ```
    pub fn run_system<O: 'static>(&self, system: SystemId<(), O>) -> AccessResult<O> {
        self.run_system_with(system, ())
    }

    /// Run a stored system by their [`SystemId`] with input.
    ///
    /// # Example
    ///
    /// ```
    /// # bevy_defer::test_spawn!({
    /// let id = AsyncWorld.register_system(|input: In<f32>, time: Res<Time>| time.delta_secs() + *input);
    /// AsyncWorld.run_system_with(id, 4.0).unwrap();
    /// # });
    /// ```
    pub fn run_system_with<I: SystemInput + 'static, O: 'static>(
        &self,
        system: SystemId<I, O>,
        input: I::Inner<'_>,
    ) -> AccessResult<O> {
        with_world_mut(move |world: &mut World| {
            world
                .run_system_with(system, input)
                .map_err(|_| AccessError::SystemIdNotFound)
        })
    }

    /// Run a system that will be stored and reused upon repeated usage.
    ///
    /// # Note
    ///
    /// The system is disambiguated by the type ID of the closure.
    /// Be careful not to pass in a `fn`.
    ///
    /// # Example
    ///
    /// ```
    /// # bevy_defer::test_spawn!({
    /// AsyncWorld.run_system_cached(|time: Res<Time>| println!("{}", time.delta_secs())).unwrap();
    /// # });
    /// ```
    pub fn run_system_cached<O: 'static, M, S: IntoSystem<(), O, M> + 'static>(
        &self,
        system: S,
    ) -> AccessResult<O> {
        with_world_mut(move |world: &mut World| {
            world
                .run_system_cached(system)
                .map_err(|_| AccessError::SystemIdNotFound)
        })
    }

    /// Run a system with input that will be stored and reused upon repeated usage.
    ///
    /// # Note
    ///
    /// The system is disambiguated by the type ID of the closure.
    /// Be careful not to pass in a `fn`.
    ///
    /// # Example
    ///
    /// ```
    /// # bevy_defer::test_spawn!({
    /// AsyncWorld.run_system_cached_with(|input: In<f32>, time: Res<Time>| time.delta_secs() + *input, 4.0).unwrap();
    /// # });
    /// ```
    pub fn run_system_cached_with<
        I: SystemInput + 'static,
        O: 'static,
        M,
        S: IntoSystem<I, O, M> + 'static,
    >(
        &self,
        system: S,
        input: I::Inner<'_>,
    ) -> AccessResult<O> {
        with_world_mut(move |world: &mut World| {
            world
                .run_system_cached_with(system, input)
                .map_err(|_| AccessError::SystemIdNotFound)
        })
    }

    /// Spawns a new [`Entity`] with no components.
    ///
    /// # Example
    ///
    /// ```
    /// # bevy_defer::test_spawn!(
    /// AsyncWorld.spawn_empty()
    /// # );
    /// ```
    pub fn spawn_empty(&self) -> AsyncEntityMut {
        self.entity(with_world_mut(move |world: &mut World| {
            world.spawn_empty().id()
        }))
    }

    /// Spawn a new [`Entity`] with a given Bundle of components.
    ///
    /// # Example
    ///
    /// ```
    /// # bevy_defer::test_spawn!(
    /// AsyncWorld.spawn_bundle(Int(4))
    /// # );
    /// ```
    pub fn spawn_bundle(&self, bundle: impl Bundle) -> AsyncEntityMut {
        self.entity(with_world_mut(move |world: &mut World| {
            world.spawn(bundle).id()
        }))
    }

    /// Initializes a new resource.
    ///
    /// If the resource already exists, nothing happens.
    pub fn init_resource<R: Resource + FromWorld>(&self) -> AsyncResource<R> {
        with_world_mut(move |world: &mut World| world.init_resource::<R>());
        self.resource()
    }

    /// Inserts a new resource with the given value.
    pub fn insert_resource<R: Resource>(&self, resource: R) -> AsyncResource<R> {
        with_world_mut(move |world: &mut World| world.insert_resource(resource));
        self.resource()
    }

    /// Transition to a new [`States`].
    ///
    /// # Example
    ///
    /// ```
    /// # bevy_defer::test_spawn!({
    /// AsyncWorld.set_state(MyState::A)
    /// # });
    /// ```
    pub fn set_state<S: FreelyMutableState>(&self, state: S) -> AccessResult<()> {
        with_world_mut(move |world: &mut World| {
            world
                .get_resource_mut::<NextState<S>>()
                .map(|mut s| s.set(state))
                .ok_or(AccessError::ResourceNotFound {
                    name: type_name::<State<S>>(),
                })
        })
    }

    /// Transition to a new [`States`].
    ///
    /// # Example
    ///
    /// ```
    /// # bevy_defer::test_spawn!({
    /// AsyncWorld.set_state(MyState::A)
    /// # });
    /// ```
    pub fn set_state_if_changed<S: FreelyMutableState>(&self, state: S) -> AccessResult<()> {
        with_world_mut(move |world: &mut World| {
            if world
                .get_resource::<State<S>>()
                .is_some_and(|x| x == &state)
            {
                return Ok(());
            }
            world
                .get_resource_mut::<NextState<S>>()
                .map(|mut s| s.set(state))
                .ok_or(AccessError::ResourceNotFound {
                    name: type_name::<State<S>>(),
                })
        })
    }

    /// Obtain a [`States`].
    ///
    /// # Example
    ///
    /// ```
    /// # bevy_defer::test_spawn!({
    /// AsyncWorld.get_state::<MyState>()
    /// # });
    /// ```
    pub fn get_state<S: States>(&self) -> AccessResult<S> {
        with_world_ref(|world| {
            world
                .get_resource::<State<S>>()
                .map(|s| s.get().clone())
                .ok_or(AccessError::ResourceNotFound {
                    name: type_name::<State<S>>(),
                })
        })
    }

    /// Obtain a `Stream` that reacts to changes of a [`States`].
    ///
    /// Requires system [`react_to_state`](crate::systems::react_to_state).
    pub fn state_stream<S: States>(&self) -> impl FusedStream<Item = S> + '_ {
        let signal = self.typed_signal::<StateSignal<S>>();
        signal.make_readable();
        signal.into_stream()
    }

    /// Writes a [`Message`].
    pub fn write_message<E: Message>(&self, event: E) -> AccessResult<MessageId<E>> {
        with_world_mut(move |world: &mut World| {
            world
                .write_message(event)
                .ok_or(AccessError::EventNotRegistered {
                    name: type_name::<E>(),
                })
        })
    }

    /// Trigger an observer [`Event`].
    pub fn trigger_event<E: Event>(&self, event: E)
    where
        for<'a> E::Trigger<'a>: Default,
    {
        with_world_mut(move |world: &mut World| world.trigger(event))
    }

    /// Perform a blocking operation on [`AsyncComputeTaskPool`].
    pub fn unblock<T: Send + Sync + 'static>(
        &self,
        f: impl FnOnce() -> T + Send + Sync + 'static,
    ) -> impl Future<Output = T> + 'static {
        let (mut send, recv) = async_oneshot::oneshot();
        let handle = AsyncComputeTaskPool::get().spawn(async move {
            let _ = send.send(f());
        });
        async move {
            let result = recv.await.unwrap();
            #[allow(clippy::drop_non_drop)]
            drop(handle);
            result
        }
    }

    /// Pause the future for the duration, according to the `Time` resource.
    ///
    /// # Example
    ///
    /// ```
    /// # bevy_defer::test_spawn!({
    /// AsyncWorld.sleep(5.4).await
    /// # });
    /// ```
    #[must_use = "futures do nothing unless you `.await` or poll them"]
    pub fn sleep(&self, duration: impl AsSeconds) -> MaybeChannelOut<()> {
        let duration = duration.as_duration();
        if duration <= Duration::ZERO {
            return Either::Right(ready(()));
        }
        let (sender, receiver) = channel();
        QUERY_QUEUE.with(|queue| queue.timed(duration.as_duration(), sender));
        Either::Left(receiver.into_out())
    }

    /// Pause the future for some frames, according to the `FrameCount` resource.
    ///
    /// # Example
    ///
    /// ```
    /// # bevy_defer::test_spawn!({
    /// AsyncWorld.sleep_frames(12).await
    /// # });
    /// ```
    #[must_use = "futures do nothing unless you `.await` or poll them"]
    pub fn sleep_frames(&self, frames: u32) -> MaybeChannelOut<()> {
        let (sender, receiver) = channel();
        if frames == 0 {
            return Either::Right(ready(()));
        }
        QUERY_QUEUE.with(|queue| queue.timed_frames(frames, sender));
        Either::Left(receiver.into_out())
    }

    /// Yield control back to the `bevy_defer` executor.
    ///
    /// Unlike `yield_now` from `futures_lite`,
    /// the future will be resumed on the next frame/execution point.
    pub fn yield_now(&self) -> impl Future<Output = ()> + 'static {
        let mut yielded = false;
        poll_fn(move |cx| {
            if yielded {
                return Poll::Ready(());
            }
            yielded = true;
            QUERY_QUEUE.with(|queue| queue.yielded.push_cx(cx));
            Poll::Pending
        })
    }

    /// Wake a future on the next frame.
    pub fn yield_now_cx(&self, cx: &Context) {
        if !QUERY_QUEUE.is_set() {
            panic!("Can only yield in async context.")
        }
        QUERY_QUEUE.with(|queue| {
            queue.yielded.push_cx(cx);
        })
    }

    /// Shutdown the bevy app.
    ///
    /// # Example
    ///
    /// ```
    /// # bevy_defer::test_spawn!({
    /// AsyncWorld.quit()
    /// # });
    /// ```
    pub fn quit(&self) {
        with_world_mut(move |world: &mut World| {
            world.write_message(AppExit::Success);
        })
    }

    /// Obtain or init a signal by [`SignalId`].
    ///
    /// # Panics
    ///
    /// If used outside a `bevy_defer` future.
    ///
    /// # Example
    ///
    /// ```
    /// # use bevy_defer::signal_ids;
    /// # signal_ids!(MySignal: f32);
    /// # bevy_defer::test_spawn!({
    /// let signal = AsyncWorld.typed_signal::<MySignal>();
    /// signal.write(3.14);
    /// signal.read_async().await;
    /// # });
    /// ```
    pub fn typed_signal<T: SignalId>(&self) -> Value<T::Data> {
        if !REACTORS.is_set() {
            panic!("Can only obtain typed signal in async context.")
        }
        REACTORS.with(|signals| signals.get_typed::<T>())
    }
}