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
#![doc=include_str!("../README.md")]
#![allow(clippy::type_complexity)]
use std::{borrow::Borrow, pin::Pin};

use bevy_app::{App, Plugin, PreUpdate, Update, PostUpdate, First};
mod async_world;
mod async_entity;
mod async_values;
mod async_systems;
mod async_query;
mod event;
pub mod signals;
mod signal_inner;
mod object;
mod executor;
mod commands;
mod anim;
pub mod ui;
use bevy_ecs::{system::{Command, Commands}, world::World};
use bevy_log::error;
pub use executor::*;
pub use async_world::*;
pub use async_systems::*;
pub use async_values::*;
pub use async_query::*;
pub use event::*;
use futures::{task::SpawnExt, Future};
pub use object::{Object, AsObject};
pub use futures::channel::oneshot::channel;

pub(crate) static CHANNEL_CLOSED: &str = "channel closed unexpectedly";

#[doc(hidden)]
pub use bevy_ecs::entity::Entity;

use signals::{SignalData, SignalId};
#[doc(hidden)]
pub use triomphe::Arc;

/// Result type of `AsyncSystemFunction`.
pub type AsyncResult<T = ()> = Result<T, AsyncFailure>;

#[derive(Debug, Default, Clone, Copy)]
/// An `bevy_defer` plugin does not run its executor by default.
/// 
/// Add [`run_async_executor!`] to your schedules to run the executor as you like.
pub struct CoreAsyncPlugin;

impl Plugin for CoreAsyncPlugin {
    fn build(&self, app: &mut App) {
        app.init_resource::<QueryQueue>()
            .init_non_send_resource::<AsyncExecutor>()
            .add_systems(First, push_async_systems);
    }
}

/// `SystemConfigs` for running the async executor once.
/// 
/// # Example
/// 
/// ```
/// app.add_systems(Update, run_async_executor!()
///     .after(some_other_system))
/// ```
#[macro_export]
macro_rules! run_async_executor {
    () => {
        bevy_ecs::system::IntoSystem::pipe(
            $crate::executor::run_async_queries,
            $crate::executor::run_async_executor,
        )
    };
}

/// An `bevy_defer` plugin that runs [`AsyncExecutor`] on [`PreUpdate`], [`Update`] and [`PostUpdate`].
#[derive(Debug, Default, Clone, Copy)]
pub struct DefaultAsyncPlugin;

impl Plugin for DefaultAsyncPlugin {
    fn build(&self, app: &mut App) {
        app.init_resource::<QueryQueue>()
            .init_non_send_resource::<AsyncExecutor>()
            .add_systems(First, push_async_systems)
            .add_systems(PreUpdate, run_async_executor!())
            .add_systems(Update, run_async_executor!())
            .add_systems(PostUpdate, run_async_executor!())
        ;
    }
}

/// Extension for [`World`], [`App`] and [`Commands`].
pub trait AsyncExtension {
    /// Spawn a task to be run on the [`AsyncExecutor`].
    fn spawn_task(&mut self, f: impl Future<Output = AsyncResult> + Send + 'static) -> &mut Self;
    /// Obtain a named signal.
    fn signal<T: SignalId>(&mut self, name: impl Borrow<str> + Into<String>) -> Arc<SignalData<T::Data>>;
}

impl AsyncExtension for World {
    fn spawn_task(&mut self, f: impl Future<Output = AsyncResult> + Send + 'static) -> &mut Self {
        let _ = self.non_send_resource::<AsyncExecutor>().0.spawner().spawn(async move {
            match f.await {
                Ok(()) => (),
                Err(err) => error!("Async Failure: {err}")
            }
        });
        self
    }

    fn signal<T: SignalId>(&mut self, name: impl Borrow<str> + Into<String>) -> Arc<SignalData<T::Data>> {
        self.get_resource_or_insert_with::<NamedSignals<T>>(Default::default).get(name)
    }
}

impl AsyncExtension for App {
    fn spawn_task(&mut self, f: impl Future<Output = AsyncResult> + Send + 'static) -> &mut Self {
        let _ = self.world.non_send_resource::<AsyncExecutor>().0.spawner().spawn(async move {
            match f.await {
                Ok(()) => (),
                Err(err) => error!("Async Failure: {err}")
            }
        });
        self
    }

    fn signal<T: SignalId>(&mut self, name: impl Borrow<str> + Into<String>) -> Arc<SignalData<T::Data>> {
        self.world.get_resource_or_insert_with::<NamedSignals<T>>(Default::default).get(name)
    }
}

impl AsyncExtension for Commands<'_, '_> {
    fn spawn_task(&mut self, f: impl Future<Output = AsyncResult> + Send + 'static) -> &mut Self {
        self.add(Spawn::new(f));
        self
    }

    fn signal<T: SignalId>(&mut self, _: impl Borrow<str> + Into<String>) -> Arc<SignalData<T::Data>> {
        unimplemented!("Cannot obtain named signal from Commands.")
    }
}

/// [`Command`] for spawning a task.
pub struct Spawn(Pin<Box<dyn Future<Output = AsyncResult> + Send + 'static>>);

impl Spawn {
    fn new(f: impl Future<Output = AsyncResult> + Send + 'static) -> Self{
        Spawn(Box::pin(f))
    }
}

impl Command for Spawn {
    fn apply(self, world: &mut World) {
        world.spawn_task(self.0);
    }
}