bevy_app/
sub_app.rs

1use crate::{App, AppLabel, InternedAppLabel, Plugin, Plugins, PluginsState};
2use bevy_ecs::{
3    event::EventRegistry,
4    prelude::*,
5    schedule::{InternedScheduleLabel, ScheduleBuildSettings, ScheduleLabel},
6    system::SystemId,
7};
8
9#[cfg(feature = "trace")]
10use bevy_utils::tracing::info_span;
11use bevy_utils::{HashMap, HashSet};
12use std::fmt::Debug;
13
14type ExtractFn = Box<dyn Fn(&mut World, &mut World) + Send>;
15
16/// A secondary application with its own [`World`]. These can run independently of each other.
17///
18/// These are useful for situations where certain processes (e.g. a render thread) need to be kept
19/// separate from the main application.
20///
21/// # Example
22///
23/// ```
24/// # use bevy_app::{App, AppLabel, SubApp, Main};
25/// # use bevy_ecs::prelude::*;
26/// # use bevy_ecs::schedule::ScheduleLabel;
27///
28/// #[derive(Resource, Default)]
29/// struct Val(pub i32);
30///
31/// #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, AppLabel)]
32/// struct ExampleApp;
33///
34/// // Create an app with a certain resource.
35/// let mut app = App::new();
36/// app.insert_resource(Val(10));
37///
38/// // Create a sub-app with the same resource and a single schedule.
39/// let mut sub_app = SubApp::new();
40/// sub_app.insert_resource(Val(100));
41///
42/// // Setup an extract function to copy the resource's value in the main world.
43/// sub_app.set_extract(|main_world, sub_world| {
44///     sub_world.resource_mut::<Val>().0 = main_world.resource::<Val>().0;
45/// });
46///
47/// // Schedule a system that will verify extraction is working.
48/// sub_app.add_systems(Main, |counter: Res<Val>| {
49///     // The value will be copied during extraction, so we should see 10 instead of 100.
50///     assert_eq!(counter.0, 10);
51/// });
52///
53/// // Add the sub-app to the main app.
54/// app.insert_sub_app(ExampleApp, sub_app);
55///
56/// // Update the application once (using the default runner).
57/// app.run();
58/// ```
59pub struct SubApp {
60    /// The data of this application.
61    world: World,
62    /// List of plugins that have been added.
63    pub(crate) plugin_registry: Vec<Box<dyn Plugin>>,
64    /// The names of plugins that have been added to this app. (used to track duplicates and
65    /// already-registered plugins)
66    pub(crate) plugin_names: HashSet<String>,
67    /// Panics if an update is attempted while plugins are building.
68    pub(crate) plugin_build_depth: usize,
69    pub(crate) plugins_state: PluginsState,
70    /// The schedule that will be run by [`update`](Self::update).
71    pub update_schedule: Option<InternedScheduleLabel>,
72    /// A function that gives mutable access to two app worlds. This is primarily
73    /// intended for copying data from the main world to secondary worlds.
74    extract: Option<ExtractFn>,
75}
76
77impl Debug for SubApp {
78    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79        write!(f, "SubApp")
80    }
81}
82
83impl Default for SubApp {
84    fn default() -> Self {
85        let mut world = World::new();
86        world.init_resource::<Schedules>();
87        Self {
88            world,
89            plugin_registry: Vec::default(),
90            plugin_names: HashSet::default(),
91            plugin_build_depth: 0,
92            plugins_state: PluginsState::Adding,
93            update_schedule: None,
94            extract: None,
95        }
96    }
97}
98
99impl SubApp {
100    /// Returns a default, empty [`SubApp`].
101    pub fn new() -> Self {
102        Self::default()
103    }
104
105    /// This method is a workaround. Each [`SubApp`] can have its own plugins, but [`Plugin`]
106    /// works on an [`App`] as a whole.
107    fn run_as_app<F>(&mut self, f: F)
108    where
109        F: FnOnce(&mut App),
110    {
111        let mut app = App::empty();
112        std::mem::swap(self, &mut app.sub_apps.main);
113        f(&mut app);
114        std::mem::swap(self, &mut app.sub_apps.main);
115    }
116
117    /// Returns a reference to the [`World`].
118    pub fn world(&self) -> &World {
119        &self.world
120    }
121
122    /// Returns a mutable reference to the [`World`].
123    pub fn world_mut(&mut self) -> &mut World {
124        &mut self.world
125    }
126
127    /// Runs the default schedule.
128    ///
129    /// Does not clear internal trackers used for change detection.
130    pub fn run_default_schedule(&mut self) {
131        if self.is_building_plugins() {
132            panic!("SubApp::update() was called while a plugin was building.");
133        }
134
135        if let Some(label) = self.update_schedule {
136            self.world.run_schedule(label);
137        }
138    }
139
140    /// Runs the default schedule and updates internal component trackers.
141    pub fn update(&mut self) {
142        self.run_default_schedule();
143        self.world.clear_trackers();
144    }
145
146    /// Extracts data from `world` into the app's world using the registered extract method.
147    ///
148    /// **Note:** There is no default extract method. Calling `extract` does nothing if
149    /// [`set_extract`](Self::set_extract) has not been called.
150    pub fn extract(&mut self, world: &mut World) {
151        if let Some(f) = self.extract.as_mut() {
152            f(world, &mut self.world);
153        }
154    }
155
156    /// Sets the method that will be called by [`extract`](Self::extract).
157    ///
158    /// The first argument is the `World` to extract data from, the second argument is the app `World`.
159    pub fn set_extract<F>(&mut self, extract: F) -> &mut Self
160    where
161        F: Fn(&mut World, &mut World) + Send + 'static,
162    {
163        self.extract = Some(Box::new(extract));
164        self
165    }
166
167    /// See [`App::insert_resource`].
168    pub fn insert_resource<R: Resource>(&mut self, resource: R) -> &mut Self {
169        self.world.insert_resource(resource);
170        self
171    }
172
173    /// See [`App::init_resource`].
174    pub fn init_resource<R: Resource + FromWorld>(&mut self) -> &mut Self {
175        self.world.init_resource::<R>();
176        self
177    }
178
179    /// See [`App::add_systems`].
180    pub fn add_systems<M>(
181        &mut self,
182        schedule: impl ScheduleLabel,
183        systems: impl IntoSystemConfigs<M>,
184    ) -> &mut Self {
185        let mut schedules = self.world.resource_mut::<Schedules>();
186        schedules.add_systems(schedule, systems);
187
188        self
189    }
190
191    /// See [`App::register_system`].
192    pub fn register_system<I: 'static, O: 'static, M, S: IntoSystem<I, O, M> + 'static>(
193        &mut self,
194        system: S,
195    ) -> SystemId<I, O> {
196        self.world.register_system(system)
197    }
198
199    /// See [`App::configure_sets`].
200    #[track_caller]
201    pub fn configure_sets(
202        &mut self,
203        schedule: impl ScheduleLabel,
204        sets: impl IntoSystemSetConfigs,
205    ) -> &mut Self {
206        let mut schedules = self.world.resource_mut::<Schedules>();
207        schedules.configure_sets(schedule, sets);
208        self
209    }
210
211    /// See [`App::add_schedule`].
212    pub fn add_schedule(&mut self, schedule: Schedule) -> &mut Self {
213        let mut schedules = self.world.resource_mut::<Schedules>();
214        schedules.insert(schedule);
215        self
216    }
217
218    /// See [`App::init_schedule`].
219    pub fn init_schedule(&mut self, label: impl ScheduleLabel) -> &mut Self {
220        let label = label.intern();
221        let mut schedules = self.world.resource_mut::<Schedules>();
222        if !schedules.contains(label) {
223            schedules.insert(Schedule::new(label));
224        }
225        self
226    }
227
228    /// See [`App::get_schedule`].
229    pub fn get_schedule(&self, label: impl ScheduleLabel) -> Option<&Schedule> {
230        let schedules = self.world.get_resource::<Schedules>()?;
231        schedules.get(label)
232    }
233
234    /// See [`App::get_schedule_mut`].
235    pub fn get_schedule_mut(&mut self, label: impl ScheduleLabel) -> Option<&mut Schedule> {
236        let schedules = self.world.get_resource_mut::<Schedules>()?;
237        // We must call `.into_inner` here because the borrow checker only understands reborrows
238        // using ordinary references, not our `Mut` smart pointers.
239        schedules.into_inner().get_mut(label)
240    }
241
242    /// See [`App::edit_schedule`].
243    pub fn edit_schedule(
244        &mut self,
245        label: impl ScheduleLabel,
246        mut f: impl FnMut(&mut Schedule),
247    ) -> &mut Self {
248        let label = label.intern();
249        let mut schedules = self.world.resource_mut::<Schedules>();
250        if !schedules.contains(label) {
251            schedules.insert(Schedule::new(label));
252        }
253
254        let schedule = schedules.get_mut(label).unwrap();
255        f(schedule);
256
257        self
258    }
259
260    /// See [`App::configure_schedules`].
261    pub fn configure_schedules(
262        &mut self,
263        schedule_build_settings: ScheduleBuildSettings,
264    ) -> &mut Self {
265        self.world_mut()
266            .resource_mut::<Schedules>()
267            .configure_schedules(schedule_build_settings);
268        self
269    }
270
271    /// See [`App::allow_ambiguous_component`].
272    pub fn allow_ambiguous_component<T: Component>(&mut self) -> &mut Self {
273        self.world_mut().allow_ambiguous_component::<T>();
274        self
275    }
276
277    /// See [`App::allow_ambiguous_resource`].
278    pub fn allow_ambiguous_resource<T: Resource>(&mut self) -> &mut Self {
279        self.world_mut().allow_ambiguous_resource::<T>();
280        self
281    }
282
283    /// See [`App::ignore_ambiguity`].
284    #[track_caller]
285    pub fn ignore_ambiguity<M1, M2, S1, S2>(
286        &mut self,
287        schedule: impl ScheduleLabel,
288        a: S1,
289        b: S2,
290    ) -> &mut Self
291    where
292        S1: IntoSystemSet<M1>,
293        S2: IntoSystemSet<M2>,
294    {
295        let schedule = schedule.intern();
296        let mut schedules = self.world.resource_mut::<Schedules>();
297
298        schedules.ignore_ambiguity(schedule, a, b);
299
300        self
301    }
302
303    /// See [`App::add_event`].
304    pub fn add_event<T>(&mut self) -> &mut Self
305    where
306        T: Event,
307    {
308        if !self.world.contains_resource::<Events<T>>() {
309            EventRegistry::register_event::<T>(self.world_mut());
310        }
311
312        self
313    }
314
315    /// See [`App::add_plugins`].
316    pub fn add_plugins<M>(&mut self, plugins: impl Plugins<M>) -> &mut Self {
317        self.run_as_app(|app| plugins.add_to_app(app));
318        self
319    }
320
321    /// See [`App::is_plugin_added`].
322    pub fn is_plugin_added<T>(&self) -> bool
323    where
324        T: Plugin,
325    {
326        self.plugin_names.contains(std::any::type_name::<T>())
327    }
328
329    /// See [`App::get_added_plugins`].
330    pub fn get_added_plugins<T>(&self) -> Vec<&T>
331    where
332        T: Plugin,
333    {
334        self.plugin_registry
335            .iter()
336            .filter_map(|p| p.downcast_ref())
337            .collect()
338    }
339
340    /// Returns `true` if there is no plugin in the middle of being built.
341    pub(crate) fn is_building_plugins(&self) -> bool {
342        self.plugin_build_depth > 0
343    }
344
345    /// Return the state of plugins.
346    #[inline]
347    pub fn plugins_state(&mut self) -> PluginsState {
348        match self.plugins_state {
349            PluginsState::Adding => {
350                let mut state = PluginsState::Ready;
351                let plugins = std::mem::take(&mut self.plugin_registry);
352                self.run_as_app(|app| {
353                    for plugin in &plugins {
354                        if !plugin.ready(app) {
355                            state = PluginsState::Adding;
356                            return;
357                        }
358                    }
359                });
360                self.plugin_registry = plugins;
361                state
362            }
363            state => state,
364        }
365    }
366
367    /// Runs [`Plugin::finish`] for each plugin.
368    pub fn finish(&mut self) {
369        let plugins = std::mem::take(&mut self.plugin_registry);
370        self.run_as_app(|app| {
371            for plugin in &plugins {
372                plugin.finish(app);
373            }
374        });
375        self.plugin_registry = plugins;
376        self.plugins_state = PluginsState::Finished;
377    }
378
379    /// Runs [`Plugin::cleanup`] for each plugin.
380    pub fn cleanup(&mut self) {
381        let plugins = std::mem::take(&mut self.plugin_registry);
382        self.run_as_app(|app| {
383            for plugin in &plugins {
384                plugin.cleanup(app);
385            }
386        });
387        self.plugin_registry = plugins;
388        self.plugins_state = PluginsState::Cleaned;
389    }
390
391    /// See [`App::register_type`].
392    #[cfg(feature = "bevy_reflect")]
393    pub fn register_type<T: bevy_reflect::GetTypeRegistration>(&mut self) -> &mut Self {
394        let registry = self.world.resource_mut::<AppTypeRegistry>();
395        registry.write().register::<T>();
396        self
397    }
398
399    /// See [`App::register_type_data`].
400    #[cfg(feature = "bevy_reflect")]
401    pub fn register_type_data<
402        T: bevy_reflect::Reflect + bevy_reflect::TypePath,
403        D: bevy_reflect::TypeData + bevy_reflect::FromType<T>,
404    >(
405        &mut self,
406    ) -> &mut Self {
407        let registry = self.world.resource_mut::<AppTypeRegistry>();
408        registry.write().register_type_data::<T, D>();
409        self
410    }
411}
412
413/// The collection of sub-apps that belong to an [`App`].
414#[derive(Default)]
415pub struct SubApps {
416    /// The primary sub-app that contains the "main" world.
417    pub main: SubApp,
418    /// Other, labeled sub-apps.
419    pub sub_apps: HashMap<InternedAppLabel, SubApp>,
420}
421
422impl SubApps {
423    /// Calls [`update`](SubApp::update) for the main sub-app, and then calls
424    /// [`extract`](SubApp::extract) and [`update`](SubApp::update) for the rest.
425    pub fn update(&mut self) {
426        #[cfg(feature = "trace")]
427        let _bevy_update_span = info_span!("update").entered();
428        {
429            #[cfg(feature = "trace")]
430            let _bevy_frame_update_span = info_span!("main app").entered();
431            self.main.run_default_schedule();
432        }
433        for (_label, sub_app) in self.sub_apps.iter_mut() {
434            #[cfg(feature = "trace")]
435            let _sub_app_span = info_span!("sub app", name = ?_label).entered();
436            sub_app.extract(&mut self.main.world);
437            sub_app.update();
438        }
439
440        self.main.world.clear_trackers();
441    }
442
443    /// Returns an iterator over the sub-apps (starting with the main one).
444    pub fn iter(&self) -> impl Iterator<Item = &SubApp> + '_ {
445        std::iter::once(&self.main).chain(self.sub_apps.values())
446    }
447
448    /// Returns a mutable iterator over the sub-apps (starting with the main one).
449    pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut SubApp> + '_ {
450        std::iter::once(&mut self.main).chain(self.sub_apps.values_mut())
451    }
452
453    /// Extract data from the main world into the [`SubApp`] with the given label and perform an update if it exists.
454    pub fn update_subapp_by_label(&mut self, label: impl AppLabel) {
455        if let Some(sub_app) = self.sub_apps.get_mut(&label.intern()) {
456            sub_app.extract(&mut self.main.world);
457            sub_app.update();
458        }
459    }
460}