1use crate::{App, AppLabel, InternedAppLabel, Plugin, Plugins, PluginsState};
2use alloc::{boxed::Box, string::String, vec::Vec};
3use bevy_ecs::{
4 event::EventRegistry,
5 prelude::*,
6 schedule::{InternedScheduleLabel, InternedSystemSet, ScheduleBuildSettings, ScheduleLabel},
7 system::{ScheduleSystem, SystemId, SystemInput},
8};
9use bevy_platform::collections::{HashMap, HashSet};
10use core::fmt::Debug;
11
12#[cfg(feature = "trace")]
13use tracing::info_span;
14
15type ExtractFn = Box<dyn Fn(&mut World, &mut World) + Send>;
16
17pub struct SubApp {
62 world: World,
64 pub(crate) plugin_registry: Vec<Box<dyn Plugin>>,
66 pub(crate) plugin_names: HashSet<String>,
69 pub(crate) plugin_build_depth: usize,
71 pub(crate) plugins_state: PluginsState,
72 pub update_schedule: Option<InternedScheduleLabel>,
74 extract: Option<ExtractFn>,
77}
78
79impl Debug for SubApp {
80 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
81 write!(f, "SubApp")
82 }
83}
84
85impl Default for SubApp {
86 fn default() -> Self {
87 let mut world = World::new();
88 world.init_resource::<Schedules>();
89 Self {
90 world,
91 plugin_registry: Vec::default(),
92 plugin_names: HashSet::default(),
93 plugin_build_depth: 0,
94 plugins_state: PluginsState::Adding,
95 update_schedule: None,
96 extract: None,
97 }
98 }
99}
100
101impl SubApp {
102 pub fn new() -> Self {
104 Self::default()
105 }
106
107 fn run_as_app<F>(&mut self, f: F)
110 where
111 F: FnOnce(&mut App),
112 {
113 let mut app = App::empty();
114 core::mem::swap(self, &mut app.sub_apps.main);
115 f(&mut app);
116 core::mem::swap(self, &mut app.sub_apps.main);
117 }
118
119 pub fn world(&self) -> &World {
121 &self.world
122 }
123
124 pub fn world_mut(&mut self) -> &mut World {
126 &mut self.world
127 }
128
129 pub fn run_default_schedule(&mut self) {
133 if self.is_building_plugins() {
134 panic!("SubApp::update() was called while a plugin was building.");
135 }
136
137 if let Some(label) = self.update_schedule {
138 self.world.run_schedule(label);
139 }
140 }
141
142 pub fn update(&mut self) {
144 self.run_default_schedule();
145 self.world.clear_trackers();
146 }
147
148 pub fn extract(&mut self, world: &mut World) {
153 if let Some(f) = self.extract.as_mut() {
154 f(world, &mut self.world);
155 }
156 }
157
158 pub fn set_extract<F>(&mut self, extract: F) -> &mut Self
162 where
163 F: Fn(&mut World, &mut World) + Send + 'static,
164 {
165 self.extract = Some(Box::new(extract));
166 self
167 }
168
169 pub fn take_extract(&mut self) -> Option<ExtractFn> {
195 self.extract.take()
196 }
197
198 pub fn insert_resource<R: Resource>(&mut self, resource: R) -> &mut Self {
200 self.world.insert_resource(resource);
201 self
202 }
203
204 pub fn init_resource<R: Resource + FromWorld>(&mut self) -> &mut Self {
206 self.world.init_resource::<R>();
207 self
208 }
209
210 pub fn add_systems<M>(
212 &mut self,
213 schedule: impl ScheduleLabel,
214 systems: impl IntoScheduleConfigs<ScheduleSystem, M>,
215 ) -> &mut Self {
216 let mut schedules = self.world.resource_mut::<Schedules>();
217 schedules.add_systems(schedule, systems);
218
219 self
220 }
221
222 pub fn register_system<I, O, M>(
224 &mut self,
225 system: impl IntoSystem<I, O, M> + 'static,
226 ) -> SystemId<I, O>
227 where
228 I: SystemInput + 'static,
229 O: 'static,
230 {
231 self.world.register_system(system)
232 }
233
234 #[track_caller]
236 pub fn configure_sets<M>(
237 &mut self,
238 schedule: impl ScheduleLabel,
239 sets: impl IntoScheduleConfigs<InternedSystemSet, M>,
240 ) -> &mut Self {
241 let mut schedules = self.world.resource_mut::<Schedules>();
242 schedules.configure_sets(schedule, sets);
243 self
244 }
245
246 pub fn add_schedule(&mut self, schedule: Schedule) -> &mut Self {
248 let mut schedules = self.world.resource_mut::<Schedules>();
249 schedules.insert(schedule);
250 self
251 }
252
253 pub fn init_schedule(&mut self, label: impl ScheduleLabel) -> &mut Self {
255 let label = label.intern();
256 let mut schedules = self.world.resource_mut::<Schedules>();
257 if !schedules.contains(label) {
258 schedules.insert(Schedule::new(label));
259 }
260 self
261 }
262
263 pub fn get_schedule(&self, label: impl ScheduleLabel) -> Option<&Schedule> {
265 let schedules = self.world.get_resource::<Schedules>()?;
266 schedules.get(label)
267 }
268
269 pub fn get_schedule_mut(&mut self, label: impl ScheduleLabel) -> Option<&mut Schedule> {
271 let schedules = self.world.get_resource_mut::<Schedules>()?;
272 schedules.into_inner().get_mut(label)
275 }
276
277 pub fn edit_schedule(
279 &mut self,
280 label: impl ScheduleLabel,
281 mut f: impl FnMut(&mut Schedule),
282 ) -> &mut Self {
283 let label = label.intern();
284 let mut schedules = self.world.resource_mut::<Schedules>();
285 if !schedules.contains(label) {
286 schedules.insert(Schedule::new(label));
287 }
288
289 let schedule = schedules.get_mut(label).unwrap();
290 f(schedule);
291
292 self
293 }
294
295 pub fn configure_schedules(
297 &mut self,
298 schedule_build_settings: ScheduleBuildSettings,
299 ) -> &mut Self {
300 self.world_mut()
301 .resource_mut::<Schedules>()
302 .configure_schedules(schedule_build_settings);
303 self
304 }
305
306 pub fn allow_ambiguous_component<T: Component>(&mut self) -> &mut Self {
308 self.world_mut().allow_ambiguous_component::<T>();
309 self
310 }
311
312 pub fn allow_ambiguous_resource<T: Resource>(&mut self) -> &mut Self {
314 self.world_mut().allow_ambiguous_resource::<T>();
315 self
316 }
317
318 #[track_caller]
320 pub fn ignore_ambiguity<M1, M2, S1, S2>(
321 &mut self,
322 schedule: impl ScheduleLabel,
323 a: S1,
324 b: S2,
325 ) -> &mut Self
326 where
327 S1: IntoSystemSet<M1>,
328 S2: IntoSystemSet<M2>,
329 {
330 let schedule = schedule.intern();
331 let mut schedules = self.world.resource_mut::<Schedules>();
332
333 schedules.ignore_ambiguity(schedule, a, b);
334
335 self
336 }
337
338 pub fn add_event<T>(&mut self) -> &mut Self
340 where
341 T: Event,
342 {
343 if !self.world.contains_resource::<Events<T>>() {
344 EventRegistry::register_event::<T>(self.world_mut());
345 }
346
347 self
348 }
349
350 pub fn add_plugins<M>(&mut self, plugins: impl Plugins<M>) -> &mut Self {
352 self.run_as_app(|app| plugins.add_to_app(app));
353 self
354 }
355
356 pub fn is_plugin_added<T>(&self) -> bool
358 where
359 T: Plugin,
360 {
361 self.plugin_names.contains(core::any::type_name::<T>())
362 }
363
364 pub fn get_added_plugins<T>(&self) -> Vec<&T>
366 where
367 T: Plugin,
368 {
369 self.plugin_registry
370 .iter()
371 .filter_map(|p| p.downcast_ref())
372 .collect()
373 }
374
375 pub(crate) fn is_building_plugins(&self) -> bool {
377 self.plugin_build_depth > 0
378 }
379
380 #[inline]
382 pub fn plugins_state(&mut self) -> PluginsState {
383 match self.plugins_state {
384 PluginsState::Adding => {
385 let mut state = PluginsState::Ready;
386 let plugins = core::mem::take(&mut self.plugin_registry);
387 self.run_as_app(|app| {
388 for plugin in &plugins {
389 if !plugin.ready(app) {
390 state = PluginsState::Adding;
391 return;
392 }
393 }
394 });
395 self.plugin_registry = plugins;
396 state
397 }
398 state => state,
399 }
400 }
401
402 pub fn finish(&mut self) {
404 let plugins = core::mem::take(&mut self.plugin_registry);
405 self.run_as_app(|app| {
406 for plugin in &plugins {
407 plugin.finish(app);
408 }
409 });
410 self.plugin_registry = plugins;
411 self.plugins_state = PluginsState::Finished;
412 }
413
414 pub fn cleanup(&mut self) {
416 let plugins = core::mem::take(&mut self.plugin_registry);
417 self.run_as_app(|app| {
418 for plugin in &plugins {
419 plugin.cleanup(app);
420 }
421 });
422 self.plugin_registry = plugins;
423 self.plugins_state = PluginsState::Cleaned;
424 }
425
426 #[cfg(feature = "bevy_reflect")]
428 pub fn register_type<T: bevy_reflect::GetTypeRegistration>(&mut self) -> &mut Self {
429 let registry = self.world.resource_mut::<AppTypeRegistry>();
430 registry.write().register::<T>();
431 self
432 }
433
434 #[cfg(feature = "bevy_reflect")]
436 pub fn register_type_data<
437 T: bevy_reflect::Reflect + bevy_reflect::TypePath,
438 D: bevy_reflect::TypeData + bevy_reflect::FromType<T>,
439 >(
440 &mut self,
441 ) -> &mut Self {
442 let registry = self.world.resource_mut::<AppTypeRegistry>();
443 registry.write().register_type_data::<T, D>();
444 self
445 }
446
447 #[cfg(feature = "reflect_functions")]
449 pub fn register_function<F, Marker>(&mut self, function: F) -> &mut Self
450 where
451 F: bevy_reflect::func::IntoFunction<'static, Marker> + 'static,
452 {
453 let registry = self.world.resource_mut::<AppFunctionRegistry>();
454 registry.write().register(function).unwrap();
455 self
456 }
457
458 #[cfg(feature = "reflect_functions")]
460 pub fn register_function_with_name<F, Marker>(
461 &mut self,
462 name: impl Into<alloc::borrow::Cow<'static, str>>,
463 function: F,
464 ) -> &mut Self
465 where
466 F: bevy_reflect::func::IntoFunction<'static, Marker> + 'static,
467 {
468 let registry = self.world.resource_mut::<AppFunctionRegistry>();
469 registry.write().register_with_name(name, function).unwrap();
470 self
471 }
472}
473
474#[derive(Default)]
476pub struct SubApps {
477 pub main: SubApp,
479 pub sub_apps: HashMap<InternedAppLabel, SubApp>,
481}
482
483impl SubApps {
484 pub fn update(&mut self) {
487 #[cfg(feature = "trace")]
488 let _bevy_update_span = info_span!("update").entered();
489 {
490 #[cfg(feature = "trace")]
491 let _bevy_frame_update_span = info_span!("main app").entered();
492 self.main.run_default_schedule();
493 }
494 for (_label, sub_app) in self.sub_apps.iter_mut() {
495 #[cfg(feature = "trace")]
496 let _sub_app_span = info_span!("sub app", name = ?_label).entered();
497 sub_app.extract(&mut self.main.world);
498 sub_app.update();
499 }
500
501 self.main.world.clear_trackers();
502 }
503
504 pub fn iter(&self) -> impl Iterator<Item = &SubApp> + '_ {
506 core::iter::once(&self.main).chain(self.sub_apps.values())
507 }
508
509 pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut SubApp> + '_ {
511 core::iter::once(&mut self.main).chain(self.sub_apps.values_mut())
512 }
513
514 pub fn update_subapp_by_label(&mut self, label: impl AppLabel) {
516 if let Some(sub_app) = self.sub_apps.get_mut(&label.intern()) {
517 sub_app.extract(&mut self.main.world);
518 sub_app.update();
519 }
520 }
521}