docs/bevy/examples/ecs/parallel_query.rs 2.9 K · 79 lines · raw · history

1 //! Illustrates parallel queries with `ParallelIterator`.
2
3 use bevy::{ecs::batching::BatchingStrategy, prelude::*};
4 use chacha20::ChaCha8Rng;
5 use rand::{RngExt, SeedableRng};
6
7 #[derive(Component, Deref)]
8 struct Velocity(Vec2);
9
10 fn spawn_system(mut commands: Commands, asset_server: Res<AssetServer>) {
11 commands.spawn(Camera2d);
12 let texture = asset_server.load("branding/icon.png");
13
14 // We're seeding the PRNG here to make this example deterministic for testing purposes.
15 // This isn't strictly required in practical use unless you need your app to be deterministic.
16 let mut rng = ChaCha8Rng::seed_from_u64(19878367467713);
17 for z in 0..128 {
18 commands.spawn((
19 Sprite::from_image(texture.clone()),
20 Transform::from_scale(Vec3::splat(0.1))
21 .with_translation(Vec2::splat(0.0).extend(z as f32)),
22 Velocity(20.0 * Vec2::new(rng.random::<f32>() - 0.5, rng.random::<f32>() - 0.5)),
23 ));
24 }
25 }
26
27 // Move sprites according to their velocity
28 fn move_system(mut sprites: Query<(&mut Transform, &Velocity)>) {
29 // Compute the new location of each sprite in parallel on the
30 // ComputeTaskPool
31 //
32 // This example is only for demonstrative purposes. Using a
33 // ParallelIterator for an inexpensive operation like addition on only 128
34 // elements will not typically be faster than just using a normal Iterator.
35 // See the ParallelIterator documentation for more information on when
36 // to use or not use ParallelIterator over a normal Iterator.
37 sprites
38 .par_iter_mut()
39 .for_each(|(mut transform, velocity)| {
40 transform.translation += velocity.extend(0.0);
41 });
42 }
43
44 // Bounce sprites outside the window
45 fn bounce_system(window: Query<&Window>, mut sprites: Query<(&Transform, &mut Velocity)>) {
46 let Ok(window) = window.single() else {
47 return;
48 };
49 let width = window.width();
50 let height = window.height();
51 let left = width / -2.0;
52 let right = width / 2.0;
53 let bottom = height / -2.0;
54 let top = height / 2.0;
55 // The default batch size can also be overridden.
56 // In this case a batch size of 32 is chosen to limit the overhead of
57 // ParallelIterator, since negating a vector is very inexpensive.
58 sprites
59 .par_iter_mut()
60 .batching_strategy(BatchingStrategy::fixed(32))
61 .for_each(|(transform, mut v)| {
62 if !(left < transform.translation.x
63 && transform.translation.x < right
64 && bottom < transform.translation.y
65 && transform.translation.y < top)
66 {
67 // For simplicity, just reverse the velocity; don't use realistic bounces
68 v.0 = -v.0;
69 }
70 });
71 }
72
73 fn main() {
74 App::new()
75 .add_plugins(DefaultPlugins)
76 .add_systems(Startup, spawn_system)
77 .add_systems(Update, (move_system, bounce_system))
78 .run();
79 }