Struct App

Source
pub struct App { /* private fields */ }
Expand description

App is the primary API for writing user applications. It automates the setup of a standard lifecycle and provides interface glue for plugins.

A single App can contain multiple SubApp instances, but App methods only affect the “main” one. To access a particular SubApp, use get_sub_app or get_sub_app_mut.

§Examples

Here is a simple “Hello World” Bevy app:

fn main() {
   App::new()
       .add_systems(Update, hello_world_system)
       .run();
}

fn hello_world_system() {
   println!("hello world");
}

Implementations§

Source§

impl App

Source

pub fn new() -> App

Creates a new App with some default structure to enable core engine features. This is the preferred constructor for most use cases.

Examples found in repository?
examples/app/empty.rs (line 6)
5fn main() {
6    App::new().run();
7}
More examples
Hide additional examples
examples/app/empty_defaults.rs (line 6)
5fn main() {
6    App::new().add_plugins(DefaultPlugins).run();
7}
examples/hello_world.rs (line 6)
5fn main() {
6    App::new().add_systems(Update, hello_world_system).run();
7}
examples/2d/mesh2d.rs (line 6)
5fn main() {
6    App::new()
7        .add_plugins(DefaultPlugins)
8        .add_systems(Startup, setup)
9        .run();
10}
examples/2d/mesh2d_alpha_mode.rs (line 11)
10fn main() {
11    App::new()
12        .add_plugins(DefaultPlugins)
13        .add_systems(Startup, setup)
14        .run();
15}
examples/2d/mesh2d_vertex_color_texture.rs (line 7)
6fn main() {
7    App::new()
8        .add_plugins(DefaultPlugins)
9        .add_systems(Startup, setup)
10        .run();
11}
Source

pub fn empty() -> App

Creates a new empty App with minimal default configuration.

Use this constructor if you want to customize scheduling, exit handling, cleanup, etc.

Source

pub fn update(&mut self)

Runs the default schedules of all sub-apps (starting with the “main” app) once.

Examples found in repository?
examples/app/custom_loop.rs (line 22)
10fn my_runner(mut app: App) -> AppExit {
11    // Finalize plugin building, including running any necessary clean-up.
12    // This is normally completed by the default runner.
13    app.finish();
14    app.cleanup();
15
16    println!("Type stuff into the console");
17    for line in io::stdin().lines() {
18        {
19            let mut input = app.world_mut().resource_mut::<Input>();
20            input.0 = line.unwrap();
21        }
22        app.update();
23
24        if let Some(exit) = app.should_exit() {
25            return exit;
26        }
27    }
28
29    AppExit::Success
30}
More examples
Hide additional examples
examples/ecs/send_and_receive_events.rs (line 44)
24fn main() {
25    let mut app = App::new();
26    app.add_plugins(MinimalPlugins)
27        .add_event::<DebugEvent>()
28        .add_event::<A>()
29        .add_event::<B>()
30        .add_systems(Update, read_and_write_different_event_types)
31        .add_systems(
32            Update,
33            (
34                send_events,
35                debug_events,
36                send_and_receive_param_set,
37                debug_events,
38                send_and_receive_manual_event_reader,
39                debug_events,
40            )
41                .chain(),
42        );
43    // We're just going to run a few frames, so we can see and understand the output.
44    app.update();
45    // By running for longer than one frame, we can see that we're caching our cursor in the event queue properly.
46    app.update();
47}
tests/ecs/ambiguity_detection.rs (line 31)
14fn main() {
15    let mut app = App::new();
16    app.add_plugins(DefaultPlugins);
17
18    let main_app = app.main_mut();
19    configure_ambiguity_detection(main_app);
20    let render_extract_app = app.sub_app_mut(RenderExtractApp);
21    configure_ambiguity_detection(render_extract_app);
22
23    // Ambiguities in the RenderApp are currently allowed.
24    // Eventually, we should forbid these: see https://github.com/bevyengine/bevy/issues/7386
25    // Uncomment the lines below to show the current ambiguities in the RenderApp.
26    // let sub_app = app.sub_app_mut(bevy_render::RenderApp);
27    // configure_ambiguity_detection(sub_app);
28
29    app.finish();
30    app.cleanup();
31    app.update();
32
33    let main_app_ambiguities = count_ambiguities(app.main());
34    assert_eq!(
35        main_app_ambiguities.total(),
36        0,
37        "Main app has unexpected ambiguities among the following schedules: \n{main_app_ambiguities:#?}.",
38    );
39
40    // RenderApp is not checked here, because it is not within the App at this point.
41    let render_extract_ambiguities = count_ambiguities(app.sub_app(RenderExtractApp));
42    assert_eq!(
43        render_extract_ambiguities.total(),
44        0,
45        "RenderExtract app has unexpected ambiguities among the following schedules: \n{render_extract_ambiguities:#?}",
46    );
47}
examples/time/time.rs (line 46)
35fn runner(mut app: App) -> AppExit {
36    banner();
37    help();
38    let stdin = io::stdin();
39    for line in stdin.lock().lines() {
40        if let Err(err) = line {
41            println!("read err: {err:#}");
42            break;
43        }
44        match line.unwrap().as_str() {
45            "" => {
46                app.update();
47            }
48            "f" => {
49                println!("FAST: setting relative speed to 2x");
50                app.world_mut()
51                    .resource_mut::<Time<Virtual>>()
52                    .set_relative_speed(2.0);
53            }
54            "n" => {
55                println!("NORMAL: setting relative speed to 1x");
56                app.world_mut()
57                    .resource_mut::<Time<Virtual>>()
58                    .set_relative_speed(1.0);
59            }
60            "s" => {
61                println!("SLOW: setting relative speed to 0.5x");
62                app.world_mut()
63                    .resource_mut::<Time<Virtual>>()
64                    .set_relative_speed(0.5);
65            }
66            "p" => {
67                println!("PAUSE: pausing virtual clock");
68                app.world_mut().resource_mut::<Time<Virtual>>().pause();
69            }
70            "u" => {
71                println!("UNPAUSE: resuming virtual clock");
72                app.world_mut().resource_mut::<Time<Virtual>>().unpause();
73            }
74            "q" => {
75                println!("QUITTING!");
76                break;
77            }
78            _ => {
79                help();
80            }
81        }
82    }
83
84    AppExit::Success
85}
examples/ecs/system_stepping.rs (line 38)
7fn main() {
8    let mut app = App::new();
9
10    app
11        // to display log messages from Stepping resource
12        .add_plugins(LogPlugin::default())
13        .add_systems(
14            Update,
15            (
16                update_system_one,
17                // establish a dependency here to simplify descriptions below
18                update_system_two.after(update_system_one),
19                update_system_three.after(update_system_two),
20                update_system_four,
21            ),
22        )
23        .add_systems(PreUpdate, pre_update_system);
24
25    // For the simplicity of this example, we directly modify the `Stepping`
26    // resource here and run the systems with `App::update()`.  Each call to
27    // `App::update()` is the equivalent of a single frame render when using
28    // `App::run()`.
29    //
30    // In a real-world situation, the `Stepping` resource would be modified by
31    // a system based on input from the user.  A full demonstration of this can
32    // be found in the breakout example.
33    println!(
34        r#"
35    Actions: call app.update()
36     Result: All systems run normally"#
37    );
38    app.update();
39
40    println!(
41        r#"
42    Actions: Add the Stepping resource then call app.update()
43     Result: All systems run normally.  Stepping has no effect unless explicitly
44             configured for a Schedule, and Stepping has been enabled."#
45    );
46    app.insert_resource(Stepping::new());
47    app.update();
48
49    println!(
50        r#"
51    Actions: Add the Update Schedule to Stepping; enable Stepping; call
52             app.update()
53     Result: Only the systems in PreUpdate run.  When Stepping is enabled,
54             systems in the configured schedules will not run unless:
55             * Stepping::step_frame() is called
56             * Stepping::continue_frame() is called
57             * System has been configured to always run"#
58    );
59    let mut stepping = app.world_mut().resource_mut::<Stepping>();
60    stepping.add_schedule(Update).enable();
61    app.update();
62
63    println!(
64        r#"
65    Actions: call Stepping.step_frame(); call app.update()
66     Result: The PreUpdate systems run, and one Update system will run.  In
67             Stepping, step means run the next system across all the schedules 
68             that have been added to the Stepping resource."#
69    );
70    let mut stepping = app.world_mut().resource_mut::<Stepping>();
71    stepping.step_frame();
72    app.update();
73
74    println!(
75        r#"
76    Actions: call app.update()
77     Result: Only the PreUpdate systems run.  The previous call to
78             Stepping::step_frame() only applies for the next call to
79             app.update()/the next frame rendered.
80    "#
81    );
82    app.update();
83
84    println!(
85        r#"
86    Actions: call Stepping::continue_frame(); call app.update()
87     Result: PreUpdate system will run, and all remaining Update systems will
88             run.  Stepping::continue_frame() tells stepping to run all systems
89             starting after the last run system until it hits the end of the
90             frame, or it encounters a system with a breakpoint set.  In this
91             case, we previously performed a step, running one system in Update.
92             This continue will cause all remaining systems in Update to run."#
93    );
94    let mut stepping = app.world_mut().resource_mut::<Stepping>();
95    stepping.continue_frame();
96    app.update();
97
98    println!(
99        r#"
100    Actions: call Stepping::step_frame() & app.update() four times in a row
101     Result: PreUpdate system runs every time we call app.update(), along with
102             one system from the Update schedule each time.  This shows what
103             execution would look like to step through an entire frame of 
104             systems."#
105    );
106    for _ in 0..4 {
107        let mut stepping = app.world_mut().resource_mut::<Stepping>();
108        stepping.step_frame();
109        app.update();
110    }
111
112    println!(
113        r#"
114    Actions: Stepping::always_run(Update, update_system_two); step through all
115             systems
116     Result: PreUpdate system and update_system_two() will run every time we
117             call app.update().  We'll also only need to step three times to
118             execute all systems in the frame.  Stepping::always_run() allows
119             us to granularly allow systems to run when stepping is enabled."#
120    );
121    let mut stepping = app.world_mut().resource_mut::<Stepping>();
122    stepping.always_run(Update, update_system_two);
123    for _ in 0..3 {
124        let mut stepping = app.world_mut().resource_mut::<Stepping>();
125        stepping.step_frame();
126        app.update();
127    }
128
129    println!(
130        r#"
131    Actions: Stepping::never_run(Update, update_system_two); continue through
132             all systems
133     Result: All systems except update_system_two() will execute.
134             Stepping::never_run() allows us to disable systems while Stepping
135             is enabled."#
136    );
137    let mut stepping = app.world_mut().resource_mut::<Stepping>();
138    stepping.never_run(Update, update_system_two);
139    stepping.continue_frame();
140    app.update();
141
142    println!(
143        r#"
144    Actions: Stepping::set_breakpoint(Update, update_system_two); continue,
145             step, continue
146     Result: During the first continue, pre_update_system() and
147             update_system_one() will run.  update_system_four() may also run
148             as it has no dependency on update_system_two() or
149             update_system_three().  Nether update_system_two() nor
150             update_system_three() will run in the first app.update() call as
151             they form a chained dependency on update_system_one() and run
152             in order of one, two, three.  Stepping stops system execution in
153             the Update schedule when it encounters the breakpoint for
154             update_system_three().
155             During the step we run update_system_two() along with the
156             pre_update_system().
157             During the final continue pre_update_system() and
158             update_system_three() run."#
159    );
160    let mut stepping = app.world_mut().resource_mut::<Stepping>();
161    stepping.set_breakpoint(Update, update_system_two);
162    stepping.continue_frame();
163    app.update();
164    let mut stepping = app.world_mut().resource_mut::<Stepping>();
165    stepping.step_frame();
166    app.update();
167    let mut stepping = app.world_mut().resource_mut::<Stepping>();
168    stepping.continue_frame();
169    app.update();
170
171    println!(
172        r#"
173    Actions: Stepping::clear_breakpoint(Update, update_system_two); continue
174             through all systems
175     Result: All systems will run"#
176    );
177    let mut stepping = app.world_mut().resource_mut::<Stepping>();
178    stepping.clear_breakpoint(Update, update_system_two);
179    stepping.continue_frame();
180    app.update();
181
182    println!(
183        r#"
184    Actions: Stepping::disable(); app.update()
185     Result: All systems will run.  With Stepping disabled, there's no need to
186             call Stepping::step_frame() or Stepping::continue_frame() to run
187             systems in the Update schedule."#
188    );
189    let mut stepping = app.world_mut().resource_mut::<Stepping>();
190    stepping.disable();
191    app.update();
192}
Source

pub fn run(&mut self) -> AppExit

Runs the App by calling its runner.

This will (re)build the App first. For general usage, see the example on the item level documentation.

§Caveats

Calls to App::run() will never return on iOS and Web.

Headless apps can generally expect this method to return control to the caller when it completes, but that is not the case for windowed apps. Windowed apps are typically driven by an event loop and some platforms expect the program to terminate when the event loop ends.

By default, Bevy uses the winit crate for window creation.

§Panics

Panics if not all plugins have been built.

Examples found in repository?
examples/app/empty.rs (line 6)
5fn main() {
6    App::new().run();
7}
More examples
Hide additional examples
examples/app/empty_defaults.rs (line 6)
5fn main() {
6    App::new().add_plugins(DefaultPlugins).run();
7}
examples/hello_world.rs (line 6)
5fn main() {
6    App::new().add_systems(Update, hello_world_system).run();
7}
examples/2d/mesh2d.rs (line 9)
5fn main() {
6    App::new()
7        .add_plugins(DefaultPlugins)
8        .add_systems(Startup, setup)
9        .run();
10}
examples/2d/mesh2d_alpha_mode.rs (line 14)
10fn main() {
11    App::new()
12        .add_plugins(DefaultPlugins)
13        .add_systems(Startup, setup)
14        .run();
15}
examples/2d/mesh2d_vertex_color_texture.rs (line 10)
6fn main() {
7    App::new()
8        .add_plugins(DefaultPlugins)
9        .add_systems(Startup, setup)
10        .run();
11}
Source

pub fn set_runner( &mut self, f: impl FnOnce(App) -> AppExit + 'static, ) -> &mut App

Sets the function that will be called when the app is run.

The runner function f is called only once by App::run. If the presence of a main loop in the app is desired, it is the responsibility of the runner function to provide it.

The runner function is usually not set manually, but by Bevy integrated plugins (e.g. WinitPlugin).

§Examples
fn my_runner(mut app: App) -> AppExit {
    loop {
        println!("In main loop");
        app.update();
        if let Some(exit) = app.should_exit() {
            return exit;
        }
    }
}

App::new()
    .set_runner(my_runner);
Examples found in repository?
examples/app/custom_loop.rs (line 46)
43fn main() -> AppExit {
44    App::new()
45        .insert_resource(Input(String::new()))
46        .set_runner(my_runner)
47        .add_systems(Update, (print_system, exit_system))
48        .run()
49}
More examples
Hide additional examples
examples/time/time.rs (line 119)
111fn main() {
112    App::new()
113        .add_plugins(MinimalPlugins)
114        .insert_resource(Time::<Virtual>::from_max_delta(Duration::from_secs(5)))
115        .insert_resource(Time::<Fixed>::from_duration(Duration::from_secs(1)))
116        .add_systems(PreUpdate, print_real_time)
117        .add_systems(FixedUpdate, print_fixed_time)
118        .add_systems(Update, print_time)
119        .set_runner(runner)
120        .run();
121}
Source

pub fn plugins_state(&mut self) -> PluginsState

Returns the state of all plugins. This is usually called by the event loop, but can be useful for situations where you want to use App::update.

Source

pub fn finish(&mut self)

Runs Plugin::finish for each plugin. This is usually called by the event loop once all plugins are ready, but can be useful for situations where you want to use App::update.

Examples found in repository?
examples/app/custom_loop.rs (line 13)
10fn my_runner(mut app: App) -> AppExit {
11    // Finalize plugin building, including running any necessary clean-up.
12    // This is normally completed by the default runner.
13    app.finish();
14    app.cleanup();
15
16    println!("Type stuff into the console");
17    for line in io::stdin().lines() {
18        {
19            let mut input = app.world_mut().resource_mut::<Input>();
20            input.0 = line.unwrap();
21        }
22        app.update();
23
24        if let Some(exit) = app.should_exit() {
25            return exit;
26        }
27    }
28
29    AppExit::Success
30}
More examples
Hide additional examples
tests/ecs/ambiguity_detection.rs (line 29)
14fn main() {
15    let mut app = App::new();
16    app.add_plugins(DefaultPlugins);
17
18    let main_app = app.main_mut();
19    configure_ambiguity_detection(main_app);
20    let render_extract_app = app.sub_app_mut(RenderExtractApp);
21    configure_ambiguity_detection(render_extract_app);
22
23    // Ambiguities in the RenderApp are currently allowed.
24    // Eventually, we should forbid these: see https://github.com/bevyengine/bevy/issues/7386
25    // Uncomment the lines below to show the current ambiguities in the RenderApp.
26    // let sub_app = app.sub_app_mut(bevy_render::RenderApp);
27    // configure_ambiguity_detection(sub_app);
28
29    app.finish();
30    app.cleanup();
31    app.update();
32
33    let main_app_ambiguities = count_ambiguities(app.main());
34    assert_eq!(
35        main_app_ambiguities.total(),
36        0,
37        "Main app has unexpected ambiguities among the following schedules: \n{main_app_ambiguities:#?}.",
38    );
39
40    // RenderApp is not checked here, because it is not within the App at this point.
41    let render_extract_ambiguities = count_ambiguities(app.sub_app(RenderExtractApp));
42    assert_eq!(
43        render_extract_ambiguities.total(),
44        0,
45        "RenderExtract app has unexpected ambiguities among the following schedules: \n{render_extract_ambiguities:#?}",
46    );
47}
Source

pub fn cleanup(&mut self)

Runs Plugin::cleanup for each plugin. This is usually called by the event loop after App::finish, but can be useful for situations where you want to use App::update.

Examples found in repository?
examples/app/custom_loop.rs (line 14)
10fn my_runner(mut app: App) -> AppExit {
11    // Finalize plugin building, including running any necessary clean-up.
12    // This is normally completed by the default runner.
13    app.finish();
14    app.cleanup();
15
16    println!("Type stuff into the console");
17    for line in io::stdin().lines() {
18        {
19            let mut input = app.world_mut().resource_mut::<Input>();
20            input.0 = line.unwrap();
21        }
22        app.update();
23
24        if let Some(exit) = app.should_exit() {
25            return exit;
26        }
27    }
28
29    AppExit::Success
30}
More examples
Hide additional examples
tests/ecs/ambiguity_detection.rs (line 30)
14fn main() {
15    let mut app = App::new();
16    app.add_plugins(DefaultPlugins);
17
18    let main_app = app.main_mut();
19    configure_ambiguity_detection(main_app);
20    let render_extract_app = app.sub_app_mut(RenderExtractApp);
21    configure_ambiguity_detection(render_extract_app);
22
23    // Ambiguities in the RenderApp are currently allowed.
24    // Eventually, we should forbid these: see https://github.com/bevyengine/bevy/issues/7386
25    // Uncomment the lines below to show the current ambiguities in the RenderApp.
26    // let sub_app = app.sub_app_mut(bevy_render::RenderApp);
27    // configure_ambiguity_detection(sub_app);
28
29    app.finish();
30    app.cleanup();
31    app.update();
32
33    let main_app_ambiguities = count_ambiguities(app.main());
34    assert_eq!(
35        main_app_ambiguities.total(),
36        0,
37        "Main app has unexpected ambiguities among the following schedules: \n{main_app_ambiguities:#?}.",
38    );
39
40    // RenderApp is not checked here, because it is not within the App at this point.
41    let render_extract_ambiguities = count_ambiguities(app.sub_app(RenderExtractApp));
42    assert_eq!(
43        render_extract_ambiguities.total(),
44        0,
45        "RenderExtract app has unexpected ambiguities among the following schedules: \n{render_extract_ambiguities:#?}",
46    );
47}
Source

pub fn add_systems<M>( &mut self, schedule: impl ScheduleLabel, systems: impl IntoSystemConfigs<M>, ) -> &mut App

Adds one or more systems to the given schedule in this app’s Schedules.

§Examples
app.add_systems(Update, (system_a, system_b, system_c));
app.add_systems(Update, (system_a, system_b).run_if(should_run));
Examples found in repository?
examples/hello_world.rs (line 6)
5fn main() {
6    App::new().add_systems(Update, hello_world_system).run();
7}
More examples
Hide additional examples
examples/app/plugin_group.rs (line 41)
40    fn build(&self, app: &mut App) {
41        app.add_systems(Update, print_hello_system);
42    }
43}
44
45fn print_hello_system() {
46    info!("hello");
47}
48
49struct PrintWorldPlugin;
50
51impl Plugin for PrintWorldPlugin {
52    fn build(&self, app: &mut App) {
53        app.add_systems(Update, print_world_system);
54    }
examples/3d/../helpers/camera_controller.rs (line 17)
16    fn build(&self, app: &mut App) {
17        app.add_systems(Update, run_camera_controller);
18    }
examples/2d/mesh2d.rs (line 8)
5fn main() {
6    App::new()
7        .add_plugins(DefaultPlugins)
8        .add_systems(Startup, setup)
9        .run();
10}
examples/2d/mesh2d_alpha_mode.rs (line 13)
10fn main() {
11    App::new()
12        .add_plugins(DefaultPlugins)
13        .add_systems(Startup, setup)
14        .run();
15}
examples/2d/mesh2d_vertex_color_texture.rs (line 9)
6fn main() {
7    App::new()
8        .add_plugins(DefaultPlugins)
9        .add_systems(Startup, setup)
10        .run();
11}
Source

pub fn register_system<I, O, M>( &mut self, system: impl IntoSystem<I, O, M> + 'static, ) -> SystemId<I, O>
where I: SystemInput + 'static, O: 'static,

Registers a system and returns a SystemId so it can later be called by World::run_system.

It’s possible to register the same systems more than once, they’ll be stored separately.

This is different from adding systems to a Schedule with App::add_systems, because the SystemId that is returned can be used anywhere in the World to run the associated system. This allows for running systems in a push-based fashion. Using a Schedule is still preferred for most cases due to its better performance and ability to run non-conflicting systems simultaneously.

Source

pub fn configure_sets( &mut self, schedule: impl ScheduleLabel, sets: impl IntoSystemSetConfigs, ) -> &mut App

Configures a collection of system sets in the provided schedule, adding any sets that do not exist.

Examples found in repository?
examples/ecs/ecs_guide.rs (lines 330-334)
293fn main() {
294    // Bevy apps are created using the builder pattern. We use the builder to add systems,
295    // resources, and plugins to our app
296    App::new()
297        // Resources that implement the Default or FromWorld trait can be added like this:
298        .init_resource::<GameState>()
299        // Plugins are just a grouped set of app builder calls (just like we're doing here).
300        // We could easily turn our game into a plugin, but you can check out the plugin example for
301        // that :) The plugin below runs our app's "system schedule" once every 5 seconds.
302        .add_plugins(ScheduleRunnerPlugin::run_loop(Duration::from_secs(5)))
303        // `Startup` systems run exactly once BEFORE all other systems. These are generally used for
304        // app initialization code (ex: adding entities and resources)
305        .add_systems(Startup, startup_system)
306        // `Update` systems run once every update. These are generally used for "real-time app logic"
307        .add_systems(Update, print_message_system)
308        // SYSTEM EXECUTION ORDER
309        //
310        // Each system belongs to a `Schedule`, which controls the execution strategy and broad order
311        // of the systems within each tick. The `Startup` schedule holds
312        // startup systems, which are run a single time before `Update` runs. `Update` runs once per app update,
313        // which is generally one "frame" or one "tick".
314        //
315        // By default, all systems in a `Schedule` run in parallel, except when they require mutable access to a
316        // piece of data. This is efficient, but sometimes order matters.
317        // For example, we want our "game over" system to execute after all other systems to ensure
318        // we don't accidentally run the game for an extra round.
319        //
320        // You can force an explicit ordering between systems using the `.before` or `.after` methods.
321        // Systems will not be scheduled until all of the systems that they have an "ordering dependency" on have
322        // completed.
323        // There are other schedules, such as `Last` which runs at the very end of each run.
324        .add_systems(Last, print_at_end_round)
325        // We can also create new system sets, and order them relative to other system sets.
326        // Here is what our games execution order will look like:
327        // "before_round": new_player_system, new_round_system
328        // "round": print_message_system, score_system
329        // "after_round": score_check_system, game_over_system
330        .configure_sets(
331            Update,
332            // chain() will ensure sets run in the order they are listed
333            (MySet::BeforeRound, MySet::Round, MySet::AfterRound).chain(),
334        )
335        // The add_systems function is powerful. You can define complex system configurations with ease!
336        .add_systems(
337            Update,
338            (
339                // These `BeforeRound` systems will run before `Round` systems, thanks to the chained set configuration
340                (
341                    // You can also chain systems! new_round_system will run first, followed by new_player_system
342                    (new_round_system, new_player_system).chain(),
343                    exclusive_player_system,
344                )
345                    // All of the systems in the tuple above will be added to this set
346                    .in_set(MySet::BeforeRound),
347                // This `Round` system will run after the `BeforeRound` systems thanks to the chained set configuration
348                score_system.in_set(MySet::Round),
349                // These `AfterRound` systems will run after the `Round` systems thanks to the chained set configuration
350                (
351                    score_check_system,
352                    // In addition to chain(), you can also use `before(system)` and `after(system)`. This also works
353                    // with sets!
354                    game_over_system.after(score_check_system),
355                )
356                    .in_set(MySet::AfterRound),
357            ),
358        )
359        // This call to run() starts the app we just built!
360        .run();
361}
Source

pub fn add_event<T>(&mut self) -> &mut App
where T: Event,

Initializes T event handling by inserting an event queue resource (Events::<T>) and scheduling an event_update_system in First.

See Events for information on how to define events.

§Examples
app.add_event::<MyEvent>();
Examples found in repository?
examples/audio/pitch.rs (line 9)
6fn main() {
7    App::new()
8        .add_plugins(DefaultPlugins)
9        .add_event::<PlayPitch>()
10        .add_systems(Startup, setup)
11        .add_systems(Update, (play_pitch, keyboard_input_system))
12        .run();
13}
More examples
Hide additional examples
examples/async_tasks/external_source_external_thread.rs (line 12)
10fn main() {
11    App::new()
12        .add_event::<StreamEvent>()
13        .add_plugins(DefaultPlugins)
14        .add_systems(Startup, setup)
15        .add_systems(Update, (read_stream, spawn_text, move_text))
16        .run();
17}
examples/ecs/component_hooks.rs (line 53)
47fn main() {
48    App::new()
49        .add_plugins(DefaultPlugins)
50        .add_systems(Startup, setup)
51        .add_systems(Update, trigger_hooks)
52        .init_resource::<MyComponentIndex>()
53        .add_event::<MyEvent>()
54        .run();
55}
examples/ui/size_constraints.rs (line 8)
5fn main() {
6    App::new()
7        .add_plugins(DefaultPlugins)
8        .add_event::<ButtonActivatedEvent>()
9        .add_systems(Startup, setup)
10        .add_systems(Update, (update_buttons, update_radio_buttons_colors))
11        .run();
12}
examples/animation/animation_events.rs (line 12)
9fn main() {
10    App::new()
11        .add_plugins(DefaultPlugins)
12        .add_event::<MessageEvent>()
13        .add_systems(Startup, setup)
14        .add_systems(Update, animate_text_opacity)
15        .add_observer(edit_message)
16        .run();
17}
examples/app/log_layers_ecs.rs (line 106)
99fn custom_layer(app: &mut App) -> Option<BoxedLayer> {
100    let (sender, receiver) = mpsc::channel();
101
102    let layer = CaptureLayer { sender };
103    let resource = CapturedLogEvents(receiver);
104
105    app.insert_non_send_resource(resource);
106    app.add_event::<LogEvent>();
107    app.add_systems(Update, transfer_log_events);
108
109    Some(layer.boxed())
110}
Source

pub fn insert_resource<R>(&mut self, resource: R) -> &mut App
where R: Resource,

Inserts the Resource into the app, overwriting any existing resource of the same type.

There is also an init_resource for resources that have Default or FromWorld implementations.

§Examples
#[derive(Resource)]
struct MyCounter {
    counter: usize,
}

App::new()
   .insert_resource(MyCounter { counter: 0 });
Examples found in repository?
examples/ecs/system_param.rs (line 7)
5fn main() {
6    App::new()
7        .insert_resource(PlayerCount(0))
8        .add_systems(Startup, spawn)
9        .add_systems(Update, count_players)
10        .run();
11}
More examples
Hide additional examples
examples/ui/transparency_ui.rs (line 8)
6fn main() {
7    App::new()
8        .insert_resource(ClearColor(Color::BLACK))
9        .add_plugins(DefaultPlugins)
10        .add_systems(Startup, setup)
11        .run();
12}
examples/ui/z_index.rs (line 13)
11fn main() {
12    App::new()
13        .insert_resource(ClearColor(Color::BLACK))
14        .add_plugins(DefaultPlugins)
15        .add_systems(Startup, setup)
16        .run();
17}
examples/app/custom_loop.rs (line 45)
43fn main() -> AppExit {
44    App::new()
45        .insert_resource(Input(String::new()))
46        .set_runner(my_runner)
47        .add_systems(Update, (print_system, exit_system))
48        .run()
49}
examples/3d/mesh_ray_cast.rs (line 19)
14fn main() {
15    App::new()
16        .add_plugins(DefaultPlugins)
17        .add_systems(Startup, setup)
18        .add_systems(Update, bouncing_raycast)
19        .insert_resource(ClearColor(Color::BLACK))
20        .run();
21}
examples/3d/lightmaps.rs (line 8)
5fn main() {
6    App::new()
7        .add_plugins(DefaultPlugins)
8        .insert_resource(AmbientLight::NONE)
9        .add_systems(Startup, setup)
10        .add_systems(Update, add_lightmaps_to_meshes)
11        .run();
12}
Source

pub fn init_resource<R>(&mut self) -> &mut App
where R: Resource + FromWorld,

Inserts the Resource, initialized with its default value, into the app, if there is no existing instance of R.

R must implement FromWorld. If R implements Default, FromWorld will be automatically implemented and initialize the Resource with Default::default.

§Examples
#[derive(Resource)]
struct MyCounter {
    counter: usize,
}

impl Default for MyCounter {
    fn default() -> MyCounter {
        MyCounter {
            counter: 100
        }
    }
}

App::new()
    .init_resource::<MyCounter>();
Examples found in repository?
examples/camera/camera_orbit.rs (line 39)
36fn main() {
37    App::new()
38        .add_plugins(DefaultPlugins)
39        .init_resource::<CameraSettings>()
40        .add_systems(Startup, (setup, instructions))
41        .add_systems(Update, orbit)
42        .run();
43}
More examples
Hide additional examples
examples/time/timers.rs (line 8)
5fn main() {
6    App::new()
7        .add_plugins(DefaultPlugins)
8        .init_resource::<Countdown>()
9        .add_systems(Startup, setup)
10        .add_systems(Update, (countdown, print_when_completed))
11        .run();
12}
examples/ecs/component_hooks.rs (line 52)
47fn main() {
48    App::new()
49        .add_plugins(DefaultPlugins)
50        .add_systems(Startup, setup)
51        .add_systems(Update, trigger_hooks)
52        .init_resource::<MyComponentIndex>()
53        .add_event::<MyEvent>()
54        .run();
55}
examples/ui/font_atlas_debug.rs (line 10)
8fn main() {
9    App::new()
10        .init_resource::<State>()
11        .insert_resource(ClearColor(Color::BLACK))
12        .add_plugins(DefaultPlugins)
13        .add_systems(Startup, setup)
14        .add_systems(Update, (text_update_system, atlas_render_system))
15        .run();
16}
examples/3d/clearcoat.rs (line 51)
49pub fn main() {
50    App::new()
51        .init_resource::<LightMode>()
52        .add_plugins(DefaultPlugins)
53        .add_systems(Startup, setup)
54        .add_systems(Update, animate_light)
55        .add_systems(Update, animate_spheres)
56        .add_systems(Update, (handle_input, update_help_text).chain())
57        .run();
58}
examples/asset/custom_asset.rs (line 92)
89fn main() {
90    App::new()
91        .add_plugins(DefaultPlugins)
92        .init_resource::<State>()
93        .init_asset::<CustomAsset>()
94        .init_asset::<Blob>()
95        .init_asset_loader::<CustomAssetLoader>()
96        .init_asset_loader::<BlobAssetLoader>()
97        .add_systems(Startup, setup)
98        .add_systems(Update, print_on_load)
99        .run();
100}
Source

pub fn insert_non_send_resource<R>(&mut self, resource: R) -> &mut App
where R: 'static,

Inserts the !Send resource into the app, overwriting any existing resource of the same type.

There is also an init_non_send_resource for resources that implement Default

§Examples
struct MyCounter {
    counter: usize,
}

App::new()
    .insert_non_send_resource(MyCounter { counter: 0 });
Examples found in repository?
examples/app/log_layers_ecs.rs (line 105)
99fn custom_layer(app: &mut App) -> Option<BoxedLayer> {
100    let (sender, receiver) = mpsc::channel();
101
102    let layer = CaptureLayer { sender };
103    let resource = CapturedLogEvents(receiver);
104
105    app.insert_non_send_resource(resource);
106    app.add_event::<LogEvent>();
107    app.add_systems(Update, transfer_log_events);
108
109    Some(layer.boxed())
110}
Source

pub fn init_non_send_resource<R>(&mut self) -> &mut App
where R: 'static + FromWorld,

Inserts the !Send resource into the app if there is no existing instance of R.

R must implement FromWorld. If R implements Default, FromWorld will be automatically implemented and initialize the Resource with Default::default.

Source

pub fn is_plugin_added<T>(&self) -> bool
where T: Plugin,

Returns true if the Plugin has already been added.

Source

pub fn get_added_plugins<T>(&self) -> Vec<&T>
where T: Plugin,

Returns a vector of references to all plugins of type T that have been added.

This can be used to read the settings of any existing plugins. This vector will be empty if no plugins of that type have been added. If multiple copies of the same plugin are added to the App, they will be listed in insertion order in this vector.

let default_sampler = app.get_added_plugins::<ImagePlugin>()[0].default_sampler;
Source

pub fn add_plugins<M>(&mut self, plugins: impl Plugins<M>) -> &mut App

Installs a Plugin collection.

Bevy prioritizes modularity as a core principle. All engine features are implemented as plugins, even the complex ones like rendering.

Plugins can be grouped into a set by using a PluginGroup.

There are built-in PluginGroups that provide core engine functionality. The PluginGroups available by default are DefaultPlugins and MinimalPlugins.

To customize the plugins in the group (reorder, disable a plugin, add a new plugin before / after another plugin), call build() on the group, which will convert it to a PluginGroupBuilder.

You can also specify a group of Plugins by using a tuple over Plugins and PluginGroups. See Plugins for more details.

§Examples
App::new()
    .add_plugins(MinimalPlugins);
App::new()
    .add_plugins((MinimalPlugins, LogPlugin));
§Panics

Panics if one of the plugins had already been added to the application.

Examples found in repository?
examples/app/empty_defaults.rs (line 6)
5fn main() {
6    App::new().add_plugins(DefaultPlugins).run();
7}
More examples
Hide additional examples
examples/2d/mesh2d.rs (line 7)
5fn main() {
6    App::new()
7        .add_plugins(DefaultPlugins)
8        .add_systems(Startup, setup)
9        .run();
10}
examples/2d/mesh2d_alpha_mode.rs (line 12)
10fn main() {
11    App::new()
12        .add_plugins(DefaultPlugins)
13        .add_systems(Startup, setup)
14        .run();
15}
examples/2d/mesh2d_vertex_color_texture.rs (line 8)
6fn main() {
7    App::new()
8        .add_plugins(DefaultPlugins)
9        .add_systems(Startup, setup)
10        .run();
11}
examples/2d/sprite.rs (line 7)
5fn main() {
6    App::new()
7        .add_plugins(DefaultPlugins)
8        .add_systems(Startup, setup)
9        .run();
10}
examples/2d/sprite_flipping.rs (line 7)
5fn main() {
6    App::new()
7        .add_plugins(DefaultPlugins)
8        .add_systems(Startup, setup)
9        .run();
10}
Source

pub fn register_type<T>(&mut self) -> &mut App

Available on crate feature bevy_reflect only.

Registers the type T in the AppTypeRegistry resource, adding reflect data as specified in the Reflect derive:

#[derive(Component, Serialize, Deserialize, Reflect)]
#[reflect(Component, Serialize, Deserialize)] // will register ReflectComponent, ReflectSerialize, ReflectDeserialize

See bevy_reflect::TypeRegistry::register for more information.

Examples found in repository?
examples/reflection/reflection.rs (line 20)
16fn main() {
17    App::new()
18        .add_plugins(DefaultPlugins)
19        // Bar will be automatically registered as it's a dependency of Foo
20        .register_type::<Foo>()
21        .add_systems(Startup, setup)
22        .run();
23}
More examples
Hide additional examples
examples/reflection/generic_reflection.rs (line 10)
6fn main() {
7    App::new()
8        .add_plugins(DefaultPlugins)
9        // You must manually register each instance of a generic type
10        .register_type::<MyType<u32>>()
11        .add_systems(Startup, setup)
12        .run();
13}
examples/scene/scene.rs (line 8)
5fn main() {
6    App::new()
7        .add_plugins(DefaultPlugins)
8        .register_type::<ComponentA>()
9        .register_type::<ComponentB>()
10        .register_type::<ResourceA>()
11        .add_systems(
12            Startup,
13            (save_scene_system, load_scene_system, infotext_system),
14        )
15        .add_systems(Update, log_system)
16        .run();
17}
examples/remote/server.rs (line 19)
11fn main() {
12    App::new()
13        .add_plugins(DefaultPlugins)
14        .add_plugins(RemotePlugin::default())
15        .add_plugins(RemoteHttpPlugin::default())
16        .add_systems(Startup, setup)
17        .add_systems(Update, remove.run_if(input_just_pressed(KeyCode::Space)))
18        .add_systems(Update, move_cube)
19        .register_type::<Cube>()
20        .run();
21}
Source

pub fn register_type_data<T, D>(&mut self) -> &mut App
where T: Reflect + TypePath, D: TypeData + FromType<T>,

Available on crate feature bevy_reflect only.

Associates type data D with type T in the AppTypeRegistry resource.

Most of the time register_type can be used instead to register a type you derived Reflect for. However, in cases where you want to add a piece of type data that was not included in the list of #[reflect(...)] type data in the derive, or where the type is generic and cannot register e.g. ReflectSerialize unconditionally without knowing the specific type parameters, this method can be used to insert additional type data.

§Example
use bevy_app::App;
use bevy_reflect::{ReflectSerialize, ReflectDeserialize};

App::new()
    .register_type::<Option<String>>()
    .register_type_data::<Option<String>, ReflectSerialize>()
    .register_type_data::<Option<String>, ReflectDeserialize>();

See bevy_reflect::TypeRegistry::register_type_data.

Source

pub fn register_function<F, Marker>(&mut self, function: F) -> &mut App
where F: IntoFunction<'static, Marker> + 'static,

Available on crate feature reflect_functions only.

Registers the given function into the AppFunctionRegistry resource.

The given function will internally be stored as a DynamicFunction and mapped according to its name.

Because the function must have a name, anonymous functions (e.g. |a: i32, b: i32| { a + b }) and closures must instead be registered using register_function_with_name or converted to a DynamicFunction and named using DynamicFunction::with_name. Failure to do so will result in a panic.

Only types that implement IntoFunction may be registered via this method.

See FunctionRegistry::register for more information.

§Panics

Panics if a function has already been registered with the given name or if the function is missing a name (such as when it is an anonymous function).

§Examples
use bevy_app::App;

fn add(a: i32, b: i32) -> i32 {
    a + b
}

App::new().register_function(add);

Functions cannot be registered more than once.

use bevy_app::App;

fn add(a: i32, b: i32) -> i32 {
    a + b
}

App::new()
    .register_function(add)
    // Panic! A function has already been registered with the name "my_function"
    .register_function(add);

Anonymous functions and closures should be registered using register_function_with_name or given a name using DynamicFunction::with_name.

use bevy_app::App;

// Panic! Anonymous functions cannot be registered using `register_function`
App::new().register_function(|a: i32, b: i32| a + b);
Source

pub fn register_function_with_name<F, Marker>( &mut self, name: impl Into<Cow<'static, str>>, function: F, ) -> &mut App
where F: IntoFunction<'static, Marker> + 'static,

Available on crate feature reflect_functions only.

Registers the given function or closure into the AppFunctionRegistry resource using the given name.

To avoid conflicts, it’s recommended to use a unique name for the function. This can be achieved by “namespacing” the function with a unique identifier, such as the name of your crate.

For example, to register a function, add, from a crate, my_crate, you could use the name, "my_crate::add".

Another approach could be to use the type name of the function, however, it should be noted that anonymous functions do not have unique type names.

For named functions (e.g. fn add(a: i32, b: i32) -> i32 { a + b }) where a custom name is not needed, it’s recommended to use register_function instead as the generated name is guaranteed to be unique.

Only types that implement IntoFunction may be registered via this method.

See FunctionRegistry::register_with_name for more information.

§Panics

Panics if a function has already been registered with the given name.

§Examples
use bevy_app::App;

fn mul(a: i32, b: i32) -> i32 {
    a * b
}

let div = |a: i32, b: i32| a / b;

App::new()
    // Registering an anonymous function with a unique name
    .register_function_with_name("my_crate::add", |a: i32, b: i32| {
        a + b
    })
    // Registering an existing function with its type name
    .register_function_with_name(std::any::type_name_of_val(&mul), mul)
    // Registering an existing function with a custom name
    .register_function_with_name("my_crate::mul", mul)
    // Be careful not to register anonymous functions with their type name.
    // This code works but registers the function with a non-unique name like `foo::bar::{{closure}}`
    .register_function_with_name(std::any::type_name_of_val(&div), div);

Names must be unique.

use bevy_app::App;

fn one() {}
fn two() {}

App::new()
    .register_function_with_name("my_function", one)
    // Panic! A function has already been registered with the name "my_function"
    .register_function_with_name("my_function", two);
Source

pub fn register_required_components<T, R>(&mut self) -> &mut App
where T: Component, R: Component + Default,

Registers the given component R as a required component for T.

When T is added to an entity, R and its own required components will also be added if R was not already provided. The Default constructor will be used for the creation of R. If a custom constructor is desired, use App::register_required_components_with instead.

For the non-panicking version, see App::try_register_required_components.

Note that requirements must currently be registered before T is inserted into the world for the first time. Commonly, this is done in plugins. This limitation may be fixed in the future.

§Panics

Panics if R is already a directly required component for T, or if T has ever been added on an entity before the registration.

Indirect requirements through other components are allowed. In those cases, any existing requirements will only be overwritten if the new requirement is more specific.

§Example
#[derive(Component)]
struct A;

#[derive(Component, Default, PartialEq, Eq, Debug)]
struct B(usize);

#[derive(Component, Default, PartialEq, Eq, Debug)]
struct C(u32);

// Register B as required by A and C as required by B.
app.register_required_components::<A, B>();
app.register_required_components::<B, C>();

fn setup(mut commands: Commands) {
    // This will implicitly also insert B and C with their Default constructors.
    commands.spawn(A);
}

fn validate(query: Option<Single<(&A, &B, &C)>>) {
    let (a, b, c) = query.unwrap().into_inner();
    assert_eq!(b, &B(0));
    assert_eq!(c, &C(0));
}
Source

pub fn register_required_components_with<T, R>( &mut self, constructor: fn() -> R, ) -> &mut App
where T: Component, R: Component,

Registers the given component R as a required component for T.

When T is added to an entity, R and its own required components will also be added if R was not already provided. The given constructor will be used for the creation of R. If a Default constructor is desired, use App::register_required_components instead.

For the non-panicking version, see App::try_register_required_components_with.

Note that requirements must currently be registered before T is inserted into the world for the first time. Commonly, this is done in plugins. This limitation may be fixed in the future.

§Panics

Panics if R is already a directly required component for T, or if T has ever been added on an entity before the registration.

Indirect requirements through other components are allowed. In those cases, any existing requirements will only be overwritten if the new requirement is more specific.

§Example
#[derive(Component)]
struct A;

#[derive(Component, Default, PartialEq, Eq, Debug)]
struct B(usize);

#[derive(Component, Default, PartialEq, Eq, Debug)]
struct C(u32);

// Register B and C as required by A and C as required by B.
// A requiring C directly will overwrite the indirect requirement through B.
app.register_required_components::<A, B>();
app.register_required_components_with::<B, C>(|| C(1));
app.register_required_components_with::<A, C>(|| C(2));

fn setup(mut commands: Commands) {
    // This will implicitly also insert B with its Default constructor and C
    // with the custom constructor defined by A.
    commands.spawn(A);
}

fn validate(query: Option<Single<(&A, &B, &C)>>) {
    let (a, b, c) = query.unwrap().into_inner();
    assert_eq!(b, &B(0));
    assert_eq!(c, &C(2));
}
Source

pub fn try_register_required_components<T, R>( &mut self, ) -> Result<(), RequiredComponentsError>
where T: Component, R: Component + Default,

Tries to register the given component R as a required component for T.

When T is added to an entity, R and its own required components will also be added if R was not already provided. The Default constructor will be used for the creation of R. If a custom constructor is desired, use App::register_required_components_with instead.

For the panicking version, see App::register_required_components.

Note that requirements must currently be registered before T is inserted into the world for the first time. Commonly, this is done in plugins. This limitation may be fixed in the future.

§Errors

Returns a RequiredComponentsError if R is already a directly required component for T, or if T has ever been added on an entity before the registration.

Indirect requirements through other components are allowed. In those cases, any existing requirements will only be overwritten if the new requirement is more specific.

§Example
#[derive(Component)]
struct A;

#[derive(Component, Default, PartialEq, Eq, Debug)]
struct B(usize);

#[derive(Component, Default, PartialEq, Eq, Debug)]
struct C(u32);

// Register B as required by A and C as required by B.
app.register_required_components::<A, B>();
app.register_required_components::<B, C>();

// Duplicate registration! This will fail.
assert!(app.try_register_required_components::<A, B>().is_err());

fn setup(mut commands: Commands) {
    // This will implicitly also insert B and C with their Default constructors.
    commands.spawn(A);
}

fn validate(query: Option<Single<(&A, &B, &C)>>) {
    let (a, b, c) = query.unwrap().into_inner();
    assert_eq!(b, &B(0));
    assert_eq!(c, &C(0));
}
Source

pub fn try_register_required_components_with<T, R>( &mut self, constructor: fn() -> R, ) -> Result<(), RequiredComponentsError>
where T: Component, R: Component,

Tries to register the given component R as a required component for T.

When T is added to an entity, R and its own required components will also be added if R was not already provided. The given constructor will be used for the creation of R. If a Default constructor is desired, use App::register_required_components instead.

For the panicking version, see App::register_required_components_with.

Note that requirements must currently be registered before T is inserted into the world for the first time. Commonly, this is done in plugins. This limitation may be fixed in the future.

§Errors

Returns a RequiredComponentsError if R is already a directly required component for T, or if T has ever been added on an entity before the registration.

Indirect requirements through other components are allowed. In those cases, any existing requirements will only be overwritten if the new requirement is more specific.

§Example
#[derive(Component)]
struct A;

#[derive(Component, Default, PartialEq, Eq, Debug)]
struct B(usize);

#[derive(Component, Default, PartialEq, Eq, Debug)]
struct C(u32);

// Register B and C as required by A and C as required by B.
// A requiring C directly will overwrite the indirect requirement through B.
app.register_required_components::<A, B>();
app.register_required_components_with::<B, C>(|| C(1));
app.register_required_components_with::<A, C>(|| C(2));

// Duplicate registration! Even if the constructors were different, this would fail.
assert!(app.try_register_required_components_with::<B, C>(|| C(1)).is_err());

fn setup(mut commands: Commands) {
    // This will implicitly also insert B with its Default constructor and C
    // with the custom constructor defined by A.
    commands.spawn(A);
}

fn validate(query: Option<Single<(&A, &B, &C)>>) {
    let (a, b, c) = query.unwrap().into_inner();
    assert_eq!(b, &B(0));
    assert_eq!(c, &C(2));
}
Source

pub fn world(&self) -> &World

Returns a reference to the main SubApp’s World. This is the same as calling app.main().world().

Source

pub fn world_mut(&mut self) -> &mut World

Returns a mutable reference to the main SubApp’s World. This is the same as calling app.main_mut().world_mut().

Examples found in repository?
examples/app/custom_loop.rs (line 19)
10fn my_runner(mut app: App) -> AppExit {
11    // Finalize plugin building, including running any necessary clean-up.
12    // This is normally completed by the default runner.
13    app.finish();
14    app.cleanup();
15
16    println!("Type stuff into the console");
17    for line in io::stdin().lines() {
18        {
19            let mut input = app.world_mut().resource_mut::<Input>();
20            input.0 = line.unwrap();
21        }
22        app.update();
23
24        if let Some(exit) = app.should_exit() {
25            return exit;
26        }
27    }
28
29    AppExit::Success
30}
More examples
Hide additional examples
examples/2d/mesh2d_manual.rs (line 298)
296    fn build(&self, app: &mut App) {
297        // Load our custom shader
298        let mut shaders = app.world_mut().resource_mut::<Assets<Shader>>();
299        shaders.insert(
300            &COLORED_MESH2D_SHADER_HANDLE,
301            Shader::from_wgsl(COLORED_MESH2D_SHADER, file!()),
302        );
303
304        // Register our custom draw function, and add our render systems
305        app.get_sub_app_mut(RenderApp)
306            .unwrap()
307            .add_render_command::<Transparent2d, DrawColoredMesh2d>()
308            .init_resource::<SpecializedRenderPipelines<ColoredMesh2dPipeline>>()
309            .init_resource::<RenderColoredMesh2dInstances>()
310            .add_systems(
311                ExtractSchedule,
312                extract_colored_mesh2d.after(extract_mesh2d),
313            )
314            .add_systems(Render, queue_colored_mesh2d.in_set(RenderSet::QueueMeshes));
315    }
examples/games/stepping.rs (line 44)
34    fn build(&self, app: &mut App) {
35        app.add_systems(Startup, build_stepping_hint);
36        if cfg!(not(feature = "bevy_debug_stepping")) {
37            return;
38        }
39
40        // create and insert our debug schedule into the main schedule order.
41        // We need an independent schedule so we have access to all other
42        // schedules through the `Stepping` resource
43        app.init_schedule(DebugSchedule);
44        let mut order = app.world_mut().resource_mut::<MainScheduleOrder>();
45        order.insert_after(Update, DebugSchedule);
46
47        // create our stepping resource
48        let mut stepping = Stepping::new();
49        for label in &self.schedule_labels {
50            stepping.add_schedule(*label);
51        }
52        app.insert_resource(stepping);
53
54        // add our startup & stepping systems
55        app.insert_resource(State {
56            ui_top: self.top,
57            ui_left: self.left,
58            systems: Vec::new(),
59        })
60        .add_systems(
61            DebugSchedule,
62            (
63                build_ui.run_if(not(initialized)),
64                handle_input,
65                update_ui.run_if(initialized),
66            )
67                .chain(),
68        );
69    }
examples/time/time.rs (line 50)
35fn runner(mut app: App) -> AppExit {
36    banner();
37    help();
38    let stdin = io::stdin();
39    for line in stdin.lock().lines() {
40        if let Err(err) = line {
41            println!("read err: {err:#}");
42            break;
43        }
44        match line.unwrap().as_str() {
45            "" => {
46                app.update();
47            }
48            "f" => {
49                println!("FAST: setting relative speed to 2x");
50                app.world_mut()
51                    .resource_mut::<Time<Virtual>>()
52                    .set_relative_speed(2.0);
53            }
54            "n" => {
55                println!("NORMAL: setting relative speed to 1x");
56                app.world_mut()
57                    .resource_mut::<Time<Virtual>>()
58                    .set_relative_speed(1.0);
59            }
60            "s" => {
61                println!("SLOW: setting relative speed to 0.5x");
62                app.world_mut()
63                    .resource_mut::<Time<Virtual>>()
64                    .set_relative_speed(0.5);
65            }
66            "p" => {
67                println!("PAUSE: pausing virtual clock");
68                app.world_mut().resource_mut::<Time<Virtual>>().pause();
69            }
70            "u" => {
71                println!("UNPAUSE: resuming virtual clock");
72                app.world_mut().resource_mut::<Time<Virtual>>().unpause();
73            }
74            "q" => {
75                println!("QUITTING!");
76                break;
77            }
78            _ => {
79                help();
80            }
81        }
82    }
83
84    AppExit::Success
85}
examples/ecs/custom_schedule.rs (line 38)
16fn main() {
17    let mut app = App::new();
18
19    // Create a new [`Schedule`]. For demonstration purposes, we configure it to use a single threaded executor so that
20    // systems in this schedule are never run in parallel. However, this is not a requirement for custom schedules in
21    // general.
22    let mut custom_update_schedule = Schedule::new(SingleThreadedUpdate);
23    custom_update_schedule.set_executor_kind(ExecutorKind::SingleThreaded);
24
25    // Adding the schedule to the app does not automatically run the schedule. This merely registers the schedule so
26    // that systems can look it up using the `Schedules` resource.
27    app.add_schedule(custom_update_schedule);
28
29    // Bevy `App`s have a `main_schedule_label` field that configures which schedule is run by the App's `runner`.
30    // By default, this is `Main`. The `Main` schedule is responsible for running Bevy's main schedules such as
31    // `Update`, `Startup` or `Last`.
32    //
33    // We can configure the `Main` schedule to run our custom update schedule relative to the existing ones by modifying
34    // the `MainScheduleOrder` resource.
35    //
36    // Note that we modify `MainScheduleOrder` directly in `main` and not in a startup system. The reason for this is
37    // that the `MainScheduleOrder` cannot be modified from systems that are run as part of the `Main` schedule.
38    let mut main_schedule_order = app.world_mut().resource_mut::<MainScheduleOrder>();
39    main_schedule_order.insert_after(Update, SingleThreadedUpdate);
40
41    // Adding a custom startup schedule works similarly, but needs to use `insert_startup_after`
42    // instead of `insert_after`.
43    app.add_schedule(Schedule::new(CustomStartup));
44
45    let mut main_schedule_order = app.world_mut().resource_mut::<MainScheduleOrder>();
46    main_schedule_order.insert_startup_after(PreStartup, CustomStartup);
47
48    app.add_systems(SingleThreadedUpdate, single_threaded_update_system)
49        .add_systems(CustomStartup, custom_startup_system)
50        .add_systems(PreStartup, pre_startup_system)
51        .add_systems(Startup, startup_system)
52        .add_systems(First, first_system)
53        .add_systems(Update, update_system)
54        .add_systems(Last, last_system)
55        .run();
56}
examples/ecs/system_stepping.rs (line 59)
7fn main() {
8    let mut app = App::new();
9
10    app
11        // to display log messages from Stepping resource
12        .add_plugins(LogPlugin::default())
13        .add_systems(
14            Update,
15            (
16                update_system_one,
17                // establish a dependency here to simplify descriptions below
18                update_system_two.after(update_system_one),
19                update_system_three.after(update_system_two),
20                update_system_four,
21            ),
22        )
23        .add_systems(PreUpdate, pre_update_system);
24
25    // For the simplicity of this example, we directly modify the `Stepping`
26    // resource here and run the systems with `App::update()`.  Each call to
27    // `App::update()` is the equivalent of a single frame render when using
28    // `App::run()`.
29    //
30    // In a real-world situation, the `Stepping` resource would be modified by
31    // a system based on input from the user.  A full demonstration of this can
32    // be found in the breakout example.
33    println!(
34        r#"
35    Actions: call app.update()
36     Result: All systems run normally"#
37    );
38    app.update();
39
40    println!(
41        r#"
42    Actions: Add the Stepping resource then call app.update()
43     Result: All systems run normally.  Stepping has no effect unless explicitly
44             configured for a Schedule, and Stepping has been enabled."#
45    );
46    app.insert_resource(Stepping::new());
47    app.update();
48
49    println!(
50        r#"
51    Actions: Add the Update Schedule to Stepping; enable Stepping; call
52             app.update()
53     Result: Only the systems in PreUpdate run.  When Stepping is enabled,
54             systems in the configured schedules will not run unless:
55             * Stepping::step_frame() is called
56             * Stepping::continue_frame() is called
57             * System has been configured to always run"#
58    );
59    let mut stepping = app.world_mut().resource_mut::<Stepping>();
60    stepping.add_schedule(Update).enable();
61    app.update();
62
63    println!(
64        r#"
65    Actions: call Stepping.step_frame(); call app.update()
66     Result: The PreUpdate systems run, and one Update system will run.  In
67             Stepping, step means run the next system across all the schedules 
68             that have been added to the Stepping resource."#
69    );
70    let mut stepping = app.world_mut().resource_mut::<Stepping>();
71    stepping.step_frame();
72    app.update();
73
74    println!(
75        r#"
76    Actions: call app.update()
77     Result: Only the PreUpdate systems run.  The previous call to
78             Stepping::step_frame() only applies for the next call to
79             app.update()/the next frame rendered.
80    "#
81    );
82    app.update();
83
84    println!(
85        r#"
86    Actions: call Stepping::continue_frame(); call app.update()
87     Result: PreUpdate system will run, and all remaining Update systems will
88             run.  Stepping::continue_frame() tells stepping to run all systems
89             starting after the last run system until it hits the end of the
90             frame, or it encounters a system with a breakpoint set.  In this
91             case, we previously performed a step, running one system in Update.
92             This continue will cause all remaining systems in Update to run."#
93    );
94    let mut stepping = app.world_mut().resource_mut::<Stepping>();
95    stepping.continue_frame();
96    app.update();
97
98    println!(
99        r#"
100    Actions: call Stepping::step_frame() & app.update() four times in a row
101     Result: PreUpdate system runs every time we call app.update(), along with
102             one system from the Update schedule each time.  This shows what
103             execution would look like to step through an entire frame of 
104             systems."#
105    );
106    for _ in 0..4 {
107        let mut stepping = app.world_mut().resource_mut::<Stepping>();
108        stepping.step_frame();
109        app.update();
110    }
111
112    println!(
113        r#"
114    Actions: Stepping::always_run(Update, update_system_two); step through all
115             systems
116     Result: PreUpdate system and update_system_two() will run every time we
117             call app.update().  We'll also only need to step three times to
118             execute all systems in the frame.  Stepping::always_run() allows
119             us to granularly allow systems to run when stepping is enabled."#
120    );
121    let mut stepping = app.world_mut().resource_mut::<Stepping>();
122    stepping.always_run(Update, update_system_two);
123    for _ in 0..3 {
124        let mut stepping = app.world_mut().resource_mut::<Stepping>();
125        stepping.step_frame();
126        app.update();
127    }
128
129    println!(
130        r#"
131    Actions: Stepping::never_run(Update, update_system_two); continue through
132             all systems
133     Result: All systems except update_system_two() will execute.
134             Stepping::never_run() allows us to disable systems while Stepping
135             is enabled."#
136    );
137    let mut stepping = app.world_mut().resource_mut::<Stepping>();
138    stepping.never_run(Update, update_system_two);
139    stepping.continue_frame();
140    app.update();
141
142    println!(
143        r#"
144    Actions: Stepping::set_breakpoint(Update, update_system_two); continue,
145             step, continue
146     Result: During the first continue, pre_update_system() and
147             update_system_one() will run.  update_system_four() may also run
148             as it has no dependency on update_system_two() or
149             update_system_three().  Nether update_system_two() nor
150             update_system_three() will run in the first app.update() call as
151             they form a chained dependency on update_system_one() and run
152             in order of one, two, three.  Stepping stops system execution in
153             the Update schedule when it encounters the breakpoint for
154             update_system_three().
155             During the step we run update_system_two() along with the
156             pre_update_system().
157             During the final continue pre_update_system() and
158             update_system_three() run."#
159    );
160    let mut stepping = app.world_mut().resource_mut::<Stepping>();
161    stepping.set_breakpoint(Update, update_system_two);
162    stepping.continue_frame();
163    app.update();
164    let mut stepping = app.world_mut().resource_mut::<Stepping>();
165    stepping.step_frame();
166    app.update();
167    let mut stepping = app.world_mut().resource_mut::<Stepping>();
168    stepping.continue_frame();
169    app.update();
170
171    println!(
172        r#"
173    Actions: Stepping::clear_breakpoint(Update, update_system_two); continue
174             through all systems
175     Result: All systems will run"#
176    );
177    let mut stepping = app.world_mut().resource_mut::<Stepping>();
178    stepping.clear_breakpoint(Update, update_system_two);
179    stepping.continue_frame();
180    app.update();
181
182    println!(
183        r#"
184    Actions: Stepping::disable(); app.update()
185     Result: All systems will run.  With Stepping disabled, there's no need to
186             call Stepping::step_frame() or Stepping::continue_frame() to run
187             systems in the Update schedule."#
188    );
189    let mut stepping = app.world_mut().resource_mut::<Stepping>();
190    stepping.disable();
191    app.update();
192}
Source

pub fn main(&self) -> &SubApp

Returns a reference to the main SubApp.

Examples found in repository?
tests/ecs/ambiguity_detection.rs (line 33)
14fn main() {
15    let mut app = App::new();
16    app.add_plugins(DefaultPlugins);
17
18    let main_app = app.main_mut();
19    configure_ambiguity_detection(main_app);
20    let render_extract_app = app.sub_app_mut(RenderExtractApp);
21    configure_ambiguity_detection(render_extract_app);
22
23    // Ambiguities in the RenderApp are currently allowed.
24    // Eventually, we should forbid these: see https://github.com/bevyengine/bevy/issues/7386
25    // Uncomment the lines below to show the current ambiguities in the RenderApp.
26    // let sub_app = app.sub_app_mut(bevy_render::RenderApp);
27    // configure_ambiguity_detection(sub_app);
28
29    app.finish();
30    app.cleanup();
31    app.update();
32
33    let main_app_ambiguities = count_ambiguities(app.main());
34    assert_eq!(
35        main_app_ambiguities.total(),
36        0,
37        "Main app has unexpected ambiguities among the following schedules: \n{main_app_ambiguities:#?}.",
38    );
39
40    // RenderApp is not checked here, because it is not within the App at this point.
41    let render_extract_ambiguities = count_ambiguities(app.sub_app(RenderExtractApp));
42    assert_eq!(
43        render_extract_ambiguities.total(),
44        0,
45        "RenderExtract app has unexpected ambiguities among the following schedules: \n{render_extract_ambiguities:#?}",
46    );
47}
Source

pub fn main_mut(&mut self) -> &mut SubApp

Returns a mutable reference to the main SubApp.

Examples found in repository?
tests/ecs/ambiguity_detection.rs (line 18)
14fn main() {
15    let mut app = App::new();
16    app.add_plugins(DefaultPlugins);
17
18    let main_app = app.main_mut();
19    configure_ambiguity_detection(main_app);
20    let render_extract_app = app.sub_app_mut(RenderExtractApp);
21    configure_ambiguity_detection(render_extract_app);
22
23    // Ambiguities in the RenderApp are currently allowed.
24    // Eventually, we should forbid these: see https://github.com/bevyengine/bevy/issues/7386
25    // Uncomment the lines below to show the current ambiguities in the RenderApp.
26    // let sub_app = app.sub_app_mut(bevy_render::RenderApp);
27    // configure_ambiguity_detection(sub_app);
28
29    app.finish();
30    app.cleanup();
31    app.update();
32
33    let main_app_ambiguities = count_ambiguities(app.main());
34    assert_eq!(
35        main_app_ambiguities.total(),
36        0,
37        "Main app has unexpected ambiguities among the following schedules: \n{main_app_ambiguities:#?}.",
38    );
39
40    // RenderApp is not checked here, because it is not within the App at this point.
41    let render_extract_ambiguities = count_ambiguities(app.sub_app(RenderExtractApp));
42    assert_eq!(
43        render_extract_ambiguities.total(),
44        0,
45        "RenderExtract app has unexpected ambiguities among the following schedules: \n{render_extract_ambiguities:#?}",
46    );
47}
Source

pub fn sub_app(&self, label: impl AppLabel) -> &SubApp

Returns a reference to the SubApp with the given label.

§Panics

Panics if the SubApp doesn’t exist.

Examples found in repository?
tests/ecs/ambiguity_detection.rs (line 41)
14fn main() {
15    let mut app = App::new();
16    app.add_plugins(DefaultPlugins);
17
18    let main_app = app.main_mut();
19    configure_ambiguity_detection(main_app);
20    let render_extract_app = app.sub_app_mut(RenderExtractApp);
21    configure_ambiguity_detection(render_extract_app);
22
23    // Ambiguities in the RenderApp are currently allowed.
24    // Eventually, we should forbid these: see https://github.com/bevyengine/bevy/issues/7386
25    // Uncomment the lines below to show the current ambiguities in the RenderApp.
26    // let sub_app = app.sub_app_mut(bevy_render::RenderApp);
27    // configure_ambiguity_detection(sub_app);
28
29    app.finish();
30    app.cleanup();
31    app.update();
32
33    let main_app_ambiguities = count_ambiguities(app.main());
34    assert_eq!(
35        main_app_ambiguities.total(),
36        0,
37        "Main app has unexpected ambiguities among the following schedules: \n{main_app_ambiguities:#?}.",
38    );
39
40    // RenderApp is not checked here, because it is not within the App at this point.
41    let render_extract_ambiguities = count_ambiguities(app.sub_app(RenderExtractApp));
42    assert_eq!(
43        render_extract_ambiguities.total(),
44        0,
45        "RenderExtract app has unexpected ambiguities among the following schedules: \n{render_extract_ambiguities:#?}",
46    );
47}
Source

pub fn sub_app_mut(&mut self, label: impl AppLabel) -> &mut SubApp

Returns a reference to the SubApp with the given label.

§Panics

Panics if the SubApp doesn’t exist.

Examples found in repository?
examples/games/loading_screen.rs (line 301)
293        fn build(&self, app: &mut App) {
294            app.insert_resource(PipelinesReady::default());
295
296            // In order to gain access to the pipelines status, we have to
297            // go into the `RenderApp`, grab the resource from the main App
298            // and then update the pipelines status from there.
299            // Writing between these Apps can only be done through the
300            // `ExtractSchedule`.
301            app.sub_app_mut(RenderApp)
302                .add_systems(ExtractSchedule, update_pipelines_ready);
303        }
More examples
Hide additional examples
examples/shader/custom_shader_instancing.rs (line 97)
95    fn build(&self, app: &mut App) {
96        app.add_plugins(ExtractComponentPlugin::<InstanceMaterialData>::default());
97        app.sub_app_mut(RenderApp)
98            .add_render_command::<Transparent3d, DrawCustom>()
99            .init_resource::<SpecializedMeshPipelines<CustomPipeline>>()
100            .add_systems(
101                Render,
102                (
103                    queue_custom.in_set(RenderSet::QueueMeshes),
104                    prepare_instance_buffers.in_set(RenderSet::PrepareResources),
105                ),
106            );
107    }
108
109    fn finish(&self, app: &mut App) {
110        app.sub_app_mut(RenderApp).init_resource::<CustomPipeline>();
111    }
examples/shader/gpu_readback.rs (line 47)
46    fn finish(&self, app: &mut App) {
47        let render_app = app.sub_app_mut(RenderApp);
48        render_app.init_resource::<ComputePipeline>().add_systems(
49            Render,
50            prepare_bind_group
51                .in_set(RenderSet::PrepareBindGroups)
52                // We don't need to recreate the bind group every frame
53                .run_if(not(resource_exists::<GpuBufferBindGroup>)),
54        );
55
56        // Add the compute node as a top level node to the render graph
57        // This means it will only execute once per frame
58        render_app
59            .world_mut()
60            .resource_mut::<RenderGraph>()
61            .add_node(ComputeNodeLabel, ComputeNode::default());
62    }
examples/shader/compute_shader_game_of_life.rs (line 105)
101    fn build(&self, app: &mut App) {
102        // Extract the game of life image resource from the main world into the render world
103        // for operation on by the compute shader and display on the sprite.
104        app.add_plugins(ExtractResourcePlugin::<GameOfLifeImages>::default());
105        let render_app = app.sub_app_mut(RenderApp);
106        render_app.add_systems(
107            Render,
108            prepare_bind_group.in_set(RenderSet::PrepareBindGroups),
109        );
110
111        let mut render_graph = render_app.world_mut().resource_mut::<RenderGraph>();
112        render_graph.add_node(GameOfLifeLabel, GameOfLifeNode::default());
113        render_graph.add_node_edge(GameOfLifeLabel, bevy::render::graph::CameraDriverLabel);
114    }
115
116    fn finish(&self, app: &mut App) {
117        let render_app = app.sub_app_mut(RenderApp);
118        render_app.init_resource::<GameOfLifePipeline>();
119    }
examples/app/headless_renderer.rs (line 203)
198    fn build(&self, app: &mut App) {
199        let (s, r) = crossbeam_channel::unbounded();
200
201        let render_app = app
202            .insert_resource(MainWorldReceiver(r))
203            .sub_app_mut(RenderApp);
204
205        let mut graph = render_app.world_mut().resource_mut::<RenderGraph>();
206        graph.add_node(ImageCopy, ImageCopyDriver);
207        graph.add_node_edge(bevy::render::graph::CameraDriverLabel, ImageCopy);
208
209        render_app
210            .insert_resource(RenderWorldSender(s))
211            // Make ImageCopiers accessible in RenderWorld system and plugin
212            .add_systems(ExtractSchedule, image_copy_extract)
213            // Receives image data from buffer to channel
214            // so we need to run it after the render graph is done
215            .add_systems(Render, receive_image_from_buffer.after(RenderSet::Render));
216    }
tests/ecs/ambiguity_detection.rs (line 20)
14fn main() {
15    let mut app = App::new();
16    app.add_plugins(DefaultPlugins);
17
18    let main_app = app.main_mut();
19    configure_ambiguity_detection(main_app);
20    let render_extract_app = app.sub_app_mut(RenderExtractApp);
21    configure_ambiguity_detection(render_extract_app);
22
23    // Ambiguities in the RenderApp are currently allowed.
24    // Eventually, we should forbid these: see https://github.com/bevyengine/bevy/issues/7386
25    // Uncomment the lines below to show the current ambiguities in the RenderApp.
26    // let sub_app = app.sub_app_mut(bevy_render::RenderApp);
27    // configure_ambiguity_detection(sub_app);
28
29    app.finish();
30    app.cleanup();
31    app.update();
32
33    let main_app_ambiguities = count_ambiguities(app.main());
34    assert_eq!(
35        main_app_ambiguities.total(),
36        0,
37        "Main app has unexpected ambiguities among the following schedules: \n{main_app_ambiguities:#?}.",
38    );
39
40    // RenderApp is not checked here, because it is not within the App at this point.
41    let render_extract_ambiguities = count_ambiguities(app.sub_app(RenderExtractApp));
42    assert_eq!(
43        render_extract_ambiguities.total(),
44        0,
45        "RenderExtract app has unexpected ambiguities among the following schedules: \n{render_extract_ambiguities:#?}",
46    );
47}
Source

pub fn get_sub_app(&self, label: impl AppLabel) -> Option<&SubApp>

Returns a reference to the SubApp with the given label, if it exists.

Source

pub fn get_sub_app_mut(&mut self, label: impl AppLabel) -> Option<&mut SubApp>

Returns a mutable reference to the SubApp with the given label, if it exists.

Examples found in repository?
examples/stress_tests/many_lights.rs (line 157)
156    fn build(&self, app: &mut App) {
157        let Some(render_app) = app.get_sub_app_mut(RenderApp) else {
158            return;
159        };
160
161        render_app.add_systems(Render, print_visible_light_count.in_set(RenderSet::Prepare));
162    }
More examples
Hide additional examples
examples/shader/texture_binding_array.rs (line 46)
45    fn finish(&self, app: &mut App) {
46        let Some(render_app) = app.get_sub_app_mut(RenderApp) else {
47            return;
48        };
49
50        let render_device = render_app.world().resource::<RenderDevice>();
51
52        // Check if the device support the required feature. If not, exit the example.
53        // In a real application, you should setup a fallback for the missing feature
54        if !render_device
55            .features()
56            .contains(WgpuFeatures::SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING)
57        {
58            error!(
59                "Render device doesn't support feature \
60SAMPLED_TEXTURE_AND_STORAGE_BUFFER_ARRAY_NON_UNIFORM_INDEXING, \
61which is required for texture binding arrays"
62            );
63            exit(1);
64        }
65    }
examples/2d/mesh2d_manual.rs (line 305)
296    fn build(&self, app: &mut App) {
297        // Load our custom shader
298        let mut shaders = app.world_mut().resource_mut::<Assets<Shader>>();
299        shaders.insert(
300            &COLORED_MESH2D_SHADER_HANDLE,
301            Shader::from_wgsl(COLORED_MESH2D_SHADER, file!()),
302        );
303
304        // Register our custom draw function, and add our render systems
305        app.get_sub_app_mut(RenderApp)
306            .unwrap()
307            .add_render_command::<Transparent2d, DrawColoredMesh2d>()
308            .init_resource::<SpecializedRenderPipelines<ColoredMesh2dPipeline>>()
309            .init_resource::<RenderColoredMesh2dInstances>()
310            .add_systems(
311                ExtractSchedule,
312                extract_colored_mesh2d.after(extract_mesh2d),
313            )
314            .add_systems(Render, queue_colored_mesh2d.in_set(RenderSet::QueueMeshes));
315    }
316
317    fn finish(&self, app: &mut App) {
318        // Register our custom pipeline
319        app.get_sub_app_mut(RenderApp)
320            .unwrap()
321            .init_resource::<ColoredMesh2dPipeline>();
322    }
examples/shader/custom_phase_item.rs (line 182)
168fn main() {
169    let mut app = App::new();
170    app.add_plugins(DefaultPlugins)
171        .add_plugins(ExtractComponentPlugin::<CustomRenderedEntity>::default())
172        .add_systems(Startup, setup)
173        // Make sure to tell Bevy to check our entity for visibility. Bevy won't
174        // do this by default, for efficiency reasons.
175        .add_systems(
176            PostUpdate,
177            view::check_visibility::<WithCustomRenderedEntity>
178                .in_set(VisibilitySystems::CheckVisibility),
179        );
180
181    // We make sure to add these to the render app, not the main app.
182    app.get_sub_app_mut(RenderApp)
183        .unwrap()
184        .init_resource::<CustomPhasePipeline>()
185        .init_resource::<SpecializedRenderPipelines<CustomPhasePipeline>>()
186        .add_render_command::<Opaque3d, DrawCustomPhaseItemCommands>()
187        .add_systems(
188            Render,
189            prepare_custom_phase_item_buffers.in_set(RenderSet::Prepare),
190        )
191        .add_systems(Render, queue_custom_phase_item.in_set(RenderSet::Queue));
192
193    app.run();
194}
examples/shader/specialized_mesh_pipeline.rs (line 111)
99    fn build(&self, app: &mut App) {
100        app.add_plugins(ExtractComponentPlugin::<CustomRenderedEntity>::default())
101            .add_systems(
102                PostUpdate,
103                // Make sure to tell Bevy to check our entity for visibility. Bevy won't
104                // do this by default, for efficiency reasons.
105                // This will do things like frustum culling and hierarchy visibility
106                view::check_visibility::<WithCustomRenderedEntity>
107                    .in_set(VisibilitySystems::CheckVisibility),
108            );
109
110        // We make sure to add these to the render app, not the main app.
111        let Some(render_app) = app.get_sub_app_mut(RenderApp) else {
112            return;
113        };
114        render_app
115            // This is needed to tell bevy about your custom pipeline
116            .init_resource::<SpecializedMeshPipelines<CustomMeshPipeline>>()
117            // We need to use a custom draw command so we need to register it
118            .add_render_command::<Opaque3d, DrawSpecializedPipelineCommands>()
119            .add_systems(Render, queue_custom_mesh_pipeline.in_set(RenderSet::Queue));
120    }
121
122    fn finish(&self, app: &mut App) {
123        let Some(render_app) = app.get_sub_app_mut(RenderApp) else {
124            return;
125        };
126        // Creating this pipeline needs the RenderDevice and RenderQueue
127        // which are only available once rendering plugins are initialized.
128        render_app.init_resource::<CustomMeshPipeline>();
129    }
examples/shader/custom_post_processing.rs (line 65)
49    fn build(&self, app: &mut App) {
50        app.add_plugins((
51            // The settings will be a component that lives in the main world but will
52            // be extracted to the render world every frame.
53            // This makes it possible to control the effect from the main world.
54            // This plugin will take care of extracting it automatically.
55            // It's important to derive [`ExtractComponent`] on [`PostProcessingSettings`]
56            // for this plugin to work correctly.
57            ExtractComponentPlugin::<PostProcessSettings>::default(),
58            // The settings will also be the data used in the shader.
59            // This plugin will prepare the component for the GPU by creating a uniform buffer
60            // and writing the data to that buffer every frame.
61            UniformComponentPlugin::<PostProcessSettings>::default(),
62        ));
63
64        // We need to get the render app from the main app
65        let Some(render_app) = app.get_sub_app_mut(RenderApp) else {
66            return;
67        };
68
69        render_app
70            // Bevy's renderer uses a render graph which is a collection of nodes in a directed acyclic graph.
71            // It currently runs on each view/camera and executes each node in the specified order.
72            // It will make sure that any node that needs a dependency from another node
73            // only runs when that dependency is done.
74            //
75            // Each node can execute arbitrary work, but it generally runs at least one render pass.
76            // A node only has access to the render world, so if you need data from the main world
77            // you need to extract it manually or with the plugin like above.
78            // Add a [`Node`] to the [`RenderGraph`]
79            // The Node needs to impl FromWorld
80            //
81            // The [`ViewNodeRunner`] is a special [`Node`] that will automatically run the node for each view
82            // matching the [`ViewQuery`]
83            .add_render_graph_node::<ViewNodeRunner<PostProcessNode>>(
84                // Specify the label of the graph, in this case we want the graph for 3d
85                Core3d,
86                // It also needs the label of the node
87                PostProcessLabel,
88            )
89            .add_render_graph_edges(
90                Core3d,
91                // Specify the node ordering.
92                // This will automatically create all required node edges to enforce the given ordering.
93                (
94                    Node3d::Tonemapping,
95                    PostProcessLabel,
96                    Node3d::EndMainPassPostProcessing,
97                ),
98            );
99    }
100
101    fn finish(&self, app: &mut App) {
102        // We need to get the render app from the main app
103        let Some(render_app) = app.get_sub_app_mut(RenderApp) else {
104            return;
105        };
106
107        render_app
108            // Initialize the pipeline
109            .init_resource::<PostProcessPipeline>();
110    }
Source

pub fn insert_sub_app(&mut self, label: impl AppLabel, sub_app: SubApp)

Inserts a SubApp with the given label.

Source

pub fn remove_sub_app(&mut self, label: impl AppLabel) -> Option<SubApp>

Removes the SubApp with the given label, if it exists.

Source

pub fn update_sub_app_by_label(&mut self, label: impl AppLabel)

Extract data from the main world into the SubApp with the given label and perform an update if it exists.

Source

pub fn add_schedule(&mut self, schedule: Schedule) -> &mut App

Inserts a new schedule under the provided label, overwriting any existing schedule with the same label.

Examples found in repository?
examples/ecs/custom_schedule.rs (line 27)
16fn main() {
17    let mut app = App::new();
18
19    // Create a new [`Schedule`]. For demonstration purposes, we configure it to use a single threaded executor so that
20    // systems in this schedule are never run in parallel. However, this is not a requirement for custom schedules in
21    // general.
22    let mut custom_update_schedule = Schedule::new(SingleThreadedUpdate);
23    custom_update_schedule.set_executor_kind(ExecutorKind::SingleThreaded);
24
25    // Adding the schedule to the app does not automatically run the schedule. This merely registers the schedule so
26    // that systems can look it up using the `Schedules` resource.
27    app.add_schedule(custom_update_schedule);
28
29    // Bevy `App`s have a `main_schedule_label` field that configures which schedule is run by the App's `runner`.
30    // By default, this is `Main`. The `Main` schedule is responsible for running Bevy's main schedules such as
31    // `Update`, `Startup` or `Last`.
32    //
33    // We can configure the `Main` schedule to run our custom update schedule relative to the existing ones by modifying
34    // the `MainScheduleOrder` resource.
35    //
36    // Note that we modify `MainScheduleOrder` directly in `main` and not in a startup system. The reason for this is
37    // that the `MainScheduleOrder` cannot be modified from systems that are run as part of the `Main` schedule.
38    let mut main_schedule_order = app.world_mut().resource_mut::<MainScheduleOrder>();
39    main_schedule_order.insert_after(Update, SingleThreadedUpdate);
40
41    // Adding a custom startup schedule works similarly, but needs to use `insert_startup_after`
42    // instead of `insert_after`.
43    app.add_schedule(Schedule::new(CustomStartup));
44
45    let mut main_schedule_order = app.world_mut().resource_mut::<MainScheduleOrder>();
46    main_schedule_order.insert_startup_after(PreStartup, CustomStartup);
47
48    app.add_systems(SingleThreadedUpdate, single_threaded_update_system)
49        .add_systems(CustomStartup, custom_startup_system)
50        .add_systems(PreStartup, pre_startup_system)
51        .add_systems(Startup, startup_system)
52        .add_systems(First, first_system)
53        .add_systems(Update, update_system)
54        .add_systems(Last, last_system)
55        .run();
56}
Source

pub fn init_schedule(&mut self, label: impl ScheduleLabel) -> &mut App

Initializes an empty schedule under the provided label, if it does not exist.

See add_schedule to insert an existing schedule.

Examples found in repository?
examples/games/stepping.rs (line 43)
34    fn build(&self, app: &mut App) {
35        app.add_systems(Startup, build_stepping_hint);
36        if cfg!(not(feature = "bevy_debug_stepping")) {
37            return;
38        }
39
40        // create and insert our debug schedule into the main schedule order.
41        // We need an independent schedule so we have access to all other
42        // schedules through the `Stepping` resource
43        app.init_schedule(DebugSchedule);
44        let mut order = app.world_mut().resource_mut::<MainScheduleOrder>();
45        order.insert_after(Update, DebugSchedule);
46
47        // create our stepping resource
48        let mut stepping = Stepping::new();
49        for label in &self.schedule_labels {
50            stepping.add_schedule(*label);
51        }
52        app.insert_resource(stepping);
53
54        // add our startup & stepping systems
55        app.insert_resource(State {
56            ui_top: self.top,
57            ui_left: self.left,
58            systems: Vec::new(),
59        })
60        .add_systems(
61            DebugSchedule,
62            (
63                build_ui.run_if(not(initialized)),
64                handle_input,
65                update_ui.run_if(initialized),
66            )
67                .chain(),
68        );
69    }
Source

pub fn get_schedule(&self, label: impl ScheduleLabel) -> Option<&Schedule>

Returns a reference to the Schedule with the provided label if it exists.

Source

pub fn get_schedule_mut( &mut self, label: impl ScheduleLabel, ) -> Option<&mut Schedule>

Returns a mutable reference to the Schedule with the provided label if it exists.

Source

pub fn edit_schedule( &mut self, label: impl ScheduleLabel, f: impl FnMut(&mut Schedule), ) -> &mut App

Runs function f with the Schedule associated with label.

Note: This will create the schedule if it does not already exist.

Examples found in repository?
examples/ecs/nondeterministic_system_order.rs (lines 25-30)
20fn main() {
21    App::new()
22        // We can modify the reporting strategy for system execution order ambiguities on a per-schedule basis.
23        // You must do this for each schedule you want to inspect; child schedules executed within an inspected
24        // schedule do not inherit this modification.
25        .edit_schedule(Update, |schedule| {
26            schedule.set_build_settings(ScheduleBuildSettings {
27                ambiguity_detection: LogLevel::Warn,
28                ..default()
29            });
30        })
31        .init_resource::<A>()
32        .init_resource::<B>()
33        .add_systems(
34            Update,
35            (
36                // This pair of systems has an ambiguous order,
37                // as their data access conflicts, and there's no order between them.
38                reads_a,
39                writes_a,
40                // This pair of systems has conflicting data access,
41                // but it's resolved with an explicit ordering:
42                // the .after relationship here means that we will always double after adding.
43                adds_one_to_b,
44                doubles_b.after(adds_one_to_b),
45                // This system isn't ambiguous with adds_one_to_b,
46                // due to the transitive ordering created by our constraints:
47                // if A is before B is before C, then A must be before C as well.
48                reads_b.after(doubles_b),
49                // This system will conflict with all of our writing systems
50                // but we've silenced its ambiguity with adds_one_to_b.
51                // This should only be done in the case of clear false positives:
52                // leave a comment in your code justifying the decision!
53                reads_a_and_b.ambiguous_with(adds_one_to_b),
54            ),
55        )
56        // Be mindful, internal ambiguities are reported too!
57        // If there are any ambiguities due solely to DefaultPlugins,
58        // or between DefaultPlugins and any of your third party plugins,
59        // please file a bug with the repo responsible!
60        // Only *you* can prevent nondeterministic bugs due to greedy parallelism.
61        .add_plugins(DefaultPlugins)
62        .run();
63}
Source

pub fn configure_schedules( &mut self, schedule_build_settings: ScheduleBuildSettings, ) -> &mut App

Applies the provided ScheduleBuildSettings to all schedules.

Source

pub fn allow_ambiguous_component<T>(&mut self) -> &mut App
where T: Component,

When doing ambiguity checking this ignores systems that are ambiguous on Component T.

This settings only applies to the main world. To apply this to other worlds call the corresponding method on World

§Example

#[derive(Component)]
struct A;

// these systems are ambiguous on A
fn system_1(_: Query<&mut A>) {}
fn system_2(_: Query<&A>) {}

let mut app = App::new();
app.configure_schedules(ScheduleBuildSettings {
  ambiguity_detection: LogLevel::Error,
  ..default()
});

app.add_systems(Update, ( system_1, system_2 ));
app.allow_ambiguous_component::<A>();

// running the app does not error.
app.update();
Source

pub fn allow_ambiguous_resource<T>(&mut self) -> &mut App
where T: Resource,

When doing ambiguity checking this ignores systems that are ambiguous on Resource T.

This settings only applies to the main world. To apply this to other worlds call the corresponding method on World

§Example

#[derive(Resource)]
struct R;

// these systems are ambiguous on R
fn system_1(_: ResMut<R>) {}
fn system_2(_: Res<R>) {}

let mut app = App::new();
app.configure_schedules(ScheduleBuildSettings {
  ambiguity_detection: LogLevel::Error,
  ..default()
});
app.insert_resource(R);

app.add_systems(Update, ( system_1, system_2 ));
app.allow_ambiguous_resource::<R>();

// running the app does not error.
app.update();
Source

pub fn ignore_ambiguity<M1, M2, S1, S2>( &mut self, schedule: impl ScheduleLabel, a: S1, b: S2, ) -> &mut App
where S1: IntoSystemSet<M1>, S2: IntoSystemSet<M2>,

Suppress warnings and errors that would result from systems in these sets having ambiguities (conflicting access but indeterminate order) with systems in set.

When possible, do this directly in the .add_systems(Update, a.ambiguous_with(b)) call. However, sometimes two independent plugins A and B are reported as ambiguous, which you can only suppress as the consumer of both.

Source

pub fn should_exit(&self) -> Option<AppExit>

Attempts to determine if an AppExit was raised since the last update.

Will attempt to return the first Error it encounters. This should be called after every update() otherwise you risk dropping possible AppExit events.

Examples found in repository?
examples/app/custom_loop.rs (line 24)
10fn my_runner(mut app: App) -> AppExit {
11    // Finalize plugin building, including running any necessary clean-up.
12    // This is normally completed by the default runner.
13    app.finish();
14    app.cleanup();
15
16    println!("Type stuff into the console");
17    for line in io::stdin().lines() {
18        {
19            let mut input = app.world_mut().resource_mut::<Input>();
20            input.0 = line.unwrap();
21        }
22        app.update();
23
24        if let Some(exit) = app.should_exit() {
25            return exit;
26        }
27    }
28
29    AppExit::Success
30}
Source

pub fn add_observer<E, B, M>( &mut self, observer: impl IntoObserverSystem<E, B, M>, ) -> &mut App
where E: Event, B: Bundle,

Spawns an Observer entity, which will watch for and respond to the given event.

§Examples
// An observer system can be any system where the first parameter is a trigger
app.add_observer(|trigger: Trigger<Party>, friends: Query<Entity, With<Friend>>, mut commands: Commands| {
    if trigger.event().friends_allowed {
        for friend in friends.iter() {
            commands.trigger_targets(Invite, friend);
        }
    }
});
Examples found in repository?
examples/animation/animation_events.rs (line 15)
9fn main() {
10    App::new()
11        .add_plugins(DefaultPlugins)
12        .add_event::<MessageEvent>()
13        .add_systems(Startup, setup)
14        .add_systems(Update, animate_text_opacity)
15        .add_observer(edit_message)
16        .run();
17}
More examples
Hide additional examples
examples/ecs/removal_detection.rs (line 20)
13fn main() {
14    App::new()
15        .add_plugins(DefaultPlugins)
16        .add_systems(Startup, setup)
17        // This system will remove a component after two seconds.
18        .add_systems(Update, remove_component)
19        // This observer will react to the removal of the component.
20        .add_observer(react_on_removal)
21        .run();
22}
examples/ecs/observer_propagation.rs (line 17)
8fn main() {
9    App::new()
10        .add_plugins((MinimalPlugins, LogPlugin::default()))
11        .add_systems(Startup, setup)
12        .add_systems(
13            Update,
14            attack_armor.run_if(on_timer(Duration::from_millis(200))),
15        )
16        // Add a global observer that will emit a line whenever an attack hits an entity.
17        .add_observer(attack_hits)
18        .run();
19}
examples/animation/animated_fox.rs (line 27)
15fn main() {
16    App::new()
17        .insert_resource(AmbientLight {
18            color: Color::WHITE,
19            brightness: 2000.,
20        })
21        .add_plugins(DefaultPlugins)
22        .init_resource::<ParticleAssets>()
23        .init_resource::<FoxFeetTargets>()
24        .add_systems(Startup, setup)
25        .add_systems(Update, setup_scene_once_loaded)
26        .add_systems(Update, (keyboard_animation_control, simulate_particles))
27        .add_observer(observe_on_step)
28        .run();
29}
examples/ecs/observers.rs (lines 18-36)
10fn main() {
11    App::new()
12        .add_plugins(DefaultPlugins)
13        .init_resource::<SpatialIndex>()
14        .add_systems(Startup, setup)
15        .add_systems(Update, (draw_shapes, handle_click))
16        // Observers are systems that run when an event is "triggered". This observer runs whenever
17        // `ExplodeMines` is triggered.
18        .add_observer(
19            |trigger: Trigger<ExplodeMines>,
20             mines: Query<&Mine>,
21             index: Res<SpatialIndex>,
22             mut commands: Commands| {
23                // You can access the trigger data via the `Observer`
24                let event = trigger.event();
25                // Access resources
26                for e in index.get_nearby(event.pos) {
27                    // Run queries
28                    let mine = mines.get(e).unwrap();
29                    if mine.pos.distance(event.pos) < mine.size + event.radius {
30                        // And queue commands, including triggering additional events
31                        // Here we trigger the `Explode` event for entity `e`
32                        commands.trigger_targets(Explode, e);
33                    }
34                }
35            },
36        )
37        // This observer runs whenever the `Mine` component is added to an entity, and places it in a simple spatial index.
38        .add_observer(on_add_mine)
39        // This observer runs whenever the `Mine` component is removed from an entity (including despawning it)
40        // and removes it from the spatial index.
41        .add_observer(on_remove_mine)
42        .run();
43}

Trait Implementations§

Source§

impl AddAudioSource for App

Source§

fn add_audio_source<T>(&mut self) -> &mut App

Registers an audio source. The type must implement Decodable, so that it can be converted to a rodio::Source type, and Asset, so that it can be registered as an asset. To use this method on App, the audio and asset plugins must be added first.
Source§

impl AddRenderCommand for App

Source§

fn add_render_command<P, C>(&mut self) -> &mut App
where P: PhaseItem, C: RenderCommand<P> + Send + Sync + 'static, <C as RenderCommand<P>>::Param: ReadOnlySystemParam,

Adds the RenderCommand for the specified render phase to the app.
Source§

impl AppExtStates for App

Source§

fn init_state<S>(&mut self) -> &mut App

Initializes a State with standard starting values. Read more
Source§

fn insert_state<S>(&mut self, state: S) -> &mut App

Inserts a specific State to the current App and overrides any State previously added of the same type. Read more
Source§

fn add_computed_state<S>(&mut self) -> &mut App
where S: ComputedStates,

Sets up a type implementing ComputedStates. Read more
Source§

fn add_sub_state<S>(&mut self) -> &mut App
where S: SubStates,

Sets up a type implementing SubStates. Read more
Source§

fn enable_state_scoped_entities<S>(&mut self) -> &mut App
where S: States,

Enable state-scoped entity clearing for state S. Read more
Source§

fn register_type_state<S>(&mut self) -> &mut App

Available on crate feature bevy_reflect only.
Registers the state type T using App::register_type, and adds ReflectState type data to T in the type registry. Read more
Source§

fn register_type_mutable_state<S>(&mut self) -> &mut App

Available on crate feature bevy_reflect only.
Registers the state type T using App::register_type, and adds crate::reflect::ReflectState and crate::reflect::ReflectFreelyMutableState type data to T in the type registry. Read more
Source§

impl AppGizmoBuilder for App

Source§

fn init_gizmo_group<Config>(&mut self) -> &mut App
where Config: GizmoConfigGroup,

Registers GizmoConfigGroup in the app enabling the use of Gizmos<Config>. Read more
Source§

fn insert_gizmo_config<Config>( &mut self, group: Config, config: GizmoConfig, ) -> &mut App
where Config: GizmoConfigGroup,

Insert a GizmoConfig into a specific GizmoConfigGroup. Read more
Source§

impl AssetApp for App

Source§

fn register_asset_loader<L>(&mut self, loader: L) -> &mut App
where L: AssetLoader,

Registers the given loader in the App’s AssetServer.
Source§

fn register_asset_processor<P>(&mut self, processor: P) -> &mut App
where P: Process,

Registers the given processor in the App’s AssetProcessor.
Source§

fn register_asset_source( &mut self, id: impl Into<AssetSourceId<'static>>, source: AssetSourceBuilder, ) -> &mut App

Registers the given AssetSourceBuilder with the given id. Read more
Source§

fn set_default_asset_processor<P>(&mut self, extension: &str) -> &mut App
where P: Process,

Sets the default asset processor for the given extension.
Source§

fn init_asset_loader<L>(&mut self) -> &mut App

Initializes the given loader in the App’s AssetServer.
Source§

fn init_asset<A>(&mut self) -> &mut App
where A: Asset,

Initializes the given Asset in the App by: Read more
Source§

fn register_asset_reflect<A>(&mut self) -> &mut App

Registers the asset type T using [App::register], and adds ReflectAsset type data to T and ReflectHandle type data to Handle<T> in the type registry. Read more
Source§

fn preregister_asset_loader<L>(&mut self, extensions: &[&str]) -> &mut App
where L: AssetLoader,

Preregisters a loader for the given extensions, that will block asset loads until a real loader is registered.
Source§

impl Debug for App

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Default for App

Source§

fn default() -> App

Returns the “default value” for a type. Read more
Source§

impl RegisterDiagnostic for App

Source§

fn register_diagnostic(&mut self, diagnostic: Diagnostic) -> &mut App

Register a new Diagnostic with an App. Read more
Source§

impl RenderGraphApp for App

Source§

fn add_render_graph_node<T>( &mut self, sub_graph: impl RenderSubGraph, node_label: impl RenderLabel, ) -> &mut App
where T: Node + FromWorld,

Add a Node to the RenderGraph: Read more
Source§

fn add_render_graph_edge( &mut self, sub_graph: impl RenderSubGraph, output_node: impl RenderLabel, input_node: impl RenderLabel, ) -> &mut App

Add node edge to the specified graph
Source§

fn add_render_graph_edges<const N: usize>( &mut self, sub_graph: impl RenderSubGraph, edges: impl IntoRenderNodeArray<N>, ) -> &mut App

Automatically add the required node edges based on the given ordering
Source§

fn add_render_sub_graph(&mut self, sub_graph: impl RenderSubGraph) -> &mut App

Source§

impl StateScopedEventsAppExt for App

Source§

fn add_state_scoped_event<E>( &mut self, state: impl FreelyMutableState, ) -> &mut App
where E: Event,

Adds an Event that is automatically cleaned up when leaving the specified state. Read more

Auto Trait Implementations§

§

impl !Freeze for App

§

impl !RefUnwindSafe for App

§

impl !Send for App

§

impl !Sync for App

§

impl Unpin for App

§

impl !UnwindSafe for App

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T, U> AsBindGroupShaderType<U> for T
where U: ShaderType, &'a T: for<'a> Into<U>,

Source§

fn as_bind_group_shader_type(&self, _images: &RenderAssets<GpuImage>) -> U

Return the T ShaderType for self. When used in AsBindGroup derives, it is safe to assume that all images in self exist.
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> Conv for T

Source§

fn conv<T>(self) -> T
where Self: Into<T>,

Converts self into T using Into<T>. Read more
Source§

impl<T> Downcast<T> for T

Source§

fn downcast(&self) -> &T

Source§

impl<T> Downcast for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Convert Box<dyn Trait> (where Trait: Downcast) to Box<dyn Any>. Box<dyn Any> can then be further downcast into Box<ConcreteType> where ConcreteType implements Trait.
Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Convert Rc<Trait> (where Trait: Downcast) to Rc<Any>. Rc<Any> can then be further downcast into Rc<ConcreteType> where ConcreteType implements Trait.
Source§

fn as_any(&self) -> &(dyn Any + 'static)

Convert &Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &Any’s vtable from &Trait’s.
Source§

fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)

Convert &mut Trait (where Trait: Downcast) to &Any. This is needed since Rust cannot generate &mut Any’s vtable from &mut Trait’s.
Source§

impl<T> FmtForward for T

Source§

fn fmt_binary(self) -> FmtBinary<Self>
where Self: Binary,

Causes self to use its Binary implementation when Debug-formatted.
Source§

fn fmt_display(self) -> FmtDisplay<Self>
where Self: Display,

Causes self to use its Display implementation when Debug-formatted.
Source§

fn fmt_lower_exp(self) -> FmtLowerExp<Self>
where Self: LowerExp,

Causes self to use its LowerExp implementation when Debug-formatted.
Source§

fn fmt_lower_hex(self) -> FmtLowerHex<Self>
where Self: LowerHex,

Causes self to use its LowerHex implementation when Debug-formatted.
Source§

fn fmt_octal(self) -> FmtOctal<Self>
where Self: Octal,

Causes self to use its Octal implementation when Debug-formatted.
Source§

fn fmt_pointer(self) -> FmtPointer<Self>
where Self: Pointer,

Causes self to use its Pointer implementation when Debug-formatted.
Source§

fn fmt_upper_exp(self) -> FmtUpperExp<Self>
where Self: UpperExp,

Causes self to use its UpperExp implementation when Debug-formatted.
Source§

fn fmt_upper_hex(self) -> FmtUpperHex<Self>
where Self: UpperHex,

Causes self to use its UpperHex implementation when Debug-formatted.
Source§

fn fmt_list(self) -> FmtList<Self>
where &'a Self: for<'a> IntoIterator,

Formats each item in a sequence. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<S> FromSample<S> for S

Source§

fn from_sample_(s: S) -> S

Source§

impl<T> FromWorld for T
where T: Default,

Source§

fn from_world(_world: &mut World) -> T

Creates Self using default().

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<F, T> IntoSample<T> for F
where T: FromSample<F>,

Source§

fn into_sample(self) -> T

Source§

impl<T> NoneValue for T
where T: Default,

Source§

type NoneType = T

Source§

fn null_value() -> T

The none-equivalent value.
Source§

impl<T> Pipe for T
where T: ?Sized,

Source§

fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> R
where Self: Sized,

Pipes by value. This is generally the method you want to use. Read more
Source§

fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> R
where R: 'a,

Borrows self and passes that borrow into the pipe function. Read more
Source§

fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> R
where R: 'a,

Mutably borrows self and passes that borrow into the pipe function. Read more
Source§

fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
where Self: Borrow<B>, B: 'a + ?Sized, R: 'a,

Borrows self, then passes self.borrow() into the pipe function. Read more
Source§

fn pipe_borrow_mut<'a, B, R>( &'a mut self, func: impl FnOnce(&'a mut B) -> R, ) -> R
where Self: BorrowMut<B>, B: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.borrow_mut() into the pipe function. Read more
Source§

fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
where Self: AsRef<U>, U: 'a + ?Sized, R: 'a,

Borrows self, then passes self.as_ref() into the pipe function.
Source§

fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
where Self: AsMut<U>, U: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.as_mut() into the pipe function.
Source§

fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
where Self: Deref<Target = T>, T: 'a + ?Sized, R: 'a,

Borrows self, then passes self.deref() into the pipe function.
Source§

fn pipe_deref_mut<'a, T, R>( &'a mut self, func: impl FnOnce(&'a mut T) -> R, ) -> R
where Self: DerefMut<Target = T> + Deref, T: 'a + ?Sized, R: 'a,

Mutably borrows self, then passes self.deref_mut() into the pipe function.
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<R, P> ReadPrimitive<R> for P
where R: Read + ReadEndian<P>, P: Default,

Source§

fn read_from_little_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_little_endian().
Source§

fn read_from_big_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_big_endian().
Source§

fn read_from_native_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_native_endian().
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> Tap for T

Source§

fn tap(self, func: impl FnOnce(&Self)) -> Self

Immutable access to a value. Read more
Source§

fn tap_mut(self, func: impl FnOnce(&mut Self)) -> Self

Mutable access to a value. Read more
Source§

fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
where Self: Borrow<B>, B: ?Sized,

Immutable access to the Borrow<B> of a value. Read more
Source§

fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
where Self: BorrowMut<B>, B: ?Sized,

Mutable access to the BorrowMut<B> of a value. Read more
Source§

fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
where Self: AsRef<R>, R: ?Sized,

Immutable access to the AsRef<R> view of a value. Read more
Source§

fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
where Self: AsMut<R>, R: ?Sized,

Mutable access to the AsMut<R> view of a value. Read more
Source§

fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
where Self: Deref<Target = T>, T: ?Sized,

Immutable access to the Deref::Target of a value. Read more
Source§

fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
where Self: DerefMut<Target = T> + Deref, T: ?Sized,

Mutable access to the Deref::Target of a value. Read more
Source§

fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self

Calls .tap() only in debug builds, and is erased in release builds.
Source§

fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self

Calls .tap_mut() only in debug builds, and is erased in release builds.
Source§

fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
where Self: Borrow<B>, B: ?Sized,

Calls .tap_borrow() only in debug builds, and is erased in release builds.
Source§

fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
where Self: BorrowMut<B>, B: ?Sized,

Calls .tap_borrow_mut() only in debug builds, and is erased in release builds.
Source§

fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
where Self: AsRef<R>, R: ?Sized,

Calls .tap_ref() only in debug builds, and is erased in release builds.
Source§

fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
where Self: AsMut<R>, R: ?Sized,

Calls .tap_ref_mut() only in debug builds, and is erased in release builds.
Source§

fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
where Self: Deref<Target = T>, T: ?Sized,

Calls .tap_deref() only in debug builds, and is erased in release builds.
Source§

fn tap_deref_mut_dbg<T>(self, func: impl FnOnce(&mut T)) -> Self
where Self: DerefMut<Target = T> + Deref, T: ?Sized,

Calls .tap_deref_mut() only in debug builds, and is erased in release builds.
Source§

impl<T, U> ToSample<U> for T
where U: FromSample<T>,

Source§

fn to_sample_(self) -> U

Source§

impl<T> TryConv for T

Source§

fn try_conv<T>(self) -> Result<T, Self::Error>
where Self: TryInto<T>,

Attempts to convert self into T using TryInto<T>. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> Upcast<T> for T

Source§

fn upcast(&self) -> Option<&T>

Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<S, T> Duplex<S> for T
where T: FromSample<S> + ToSample<S>,