Struct bevy::ecs::system::Query

source ·
pub struct Query<'world, 'state, D, F = ()>
where D: QueryData, F: QueryFilter,
{ /* private fields */ }
Expand description

System parameter that provides selective access to the Component data stored in a World.

Enables access to entity identifiers and components from a system, without the need to directly access the world. Its iterators and getter methods return query items. Each query item is a type containing data relative to an entity.

Query is a generic data structure that accepts two type parameters:

  • D (query data). The type of data contained in the query item. Only entities that match the requested data will generate an item. Must implement the QueryData trait.
  • F (query filter). A set of conditions that determines whether query items should be kept or discarded. Must implement the QueryFilter trait. This type parameter is optional.

§System parameter declaration

A query should always be declared as a system parameter. This section shows the most common idioms involving the declaration of Query.

§Component access

A query defined with a reference to a component as the query fetch type parameter can be used to generate items that refer to the data of said component.

// A component can be accessed by shared reference...
query: Query<&ComponentA>

// ... or by mutable reference.
query: Query<&mut ComponentA>

§Query filtering

Setting the query filter type parameter will ensure that each query item satisfies the given condition.

// Just `ComponentA` data will be accessed, but only for entities that also contain
// `ComponentB`.
query: Query<&ComponentA, With<ComponentB>>

§QueryData or QueryFilter tuples

Using tuples, each Query type parameter can contain multiple elements.

In the following example, two components are accessed simultaneously, and the query items are filtered on two conditions.

query: Query<(&ComponentA, &ComponentB), (With<ComponentC>, Without<ComponentD>)>

§Entity identifier access

The identifier of an entity can be made available inside the query item by including Entity in the query fetch type parameter.

query: Query<(Entity, &ComponentA)>

§Optional component access

A component can be made optional in a query by wrapping it into an Option. In this way, a query item can still be generated even if the queried entity does not contain the wrapped component. In this case, its corresponding value will be None.

// Generates items for entities that contain `ComponentA`, and optionally `ComponentB`.
query: Query<(&ComponentA, Option<&ComponentB>)>

See the documentation for AnyOf to idiomatically declare many optional components.

See the performance section to learn more about the impact of optional components.

§Disjoint queries

A system cannot contain two queries that break Rust’s mutability rules. In this case, the Without filter can be used to disjoint them.

In the following example, two queries mutably access the same component. Executing this system will panic, since an entity could potentially match the two queries at the same time by having both Player and Enemy components. This would violate mutability rules.

fn randomize_health(
    player_query: Query<&mut Health, With<Player>>,
    enemy_query: Query<&mut Health, With<Enemy>>,
)

Adding a Without filter will disjoint the queries. In this way, any entity that has both Player and Enemy components is excluded from both queries.

fn randomize_health(
    player_query: Query<&mut Health, (With<Player>, Without<Enemy>)>,
    enemy_query: Query<&mut Health, (With<Enemy>, Without<Player>)>,
)

An alternative to this idiom is to wrap the conflicting queries into a ParamSet.

§Whole Entity Access

EntityRefs can be fetched from a query. This will give read-only access to any component on the entity, and can be use to dynamically fetch any component without baking it into the query type. Due to this global access to the entity, this will block any other system from parallelizing with it. As such these queries should be sparingly used.

query: Query<(EntityRef, &ComponentA)>

As EntityRef can read any component on an entity, a query using it will conflict with any mutable access. It is strongly advised to couple EntityRef queries with the use of either With/Without filters or ParamSets. This also limits the scope of the query, which will improve iteration performance and also allows it to parallelize with other non-conflicting systems.

// This will panic!
query: Query<(EntityRef, &mut ComponentA)>
// This will not panic.
query_a: Query<EntityRef, With<ComponentA>>,
query_b: Query<&mut ComponentB, Without<ComponentA>>,

§Accessing query items

The following table summarizes the behavior of the safe methods that can be used to get query items.

Query methodsEffect
iter[_mut]Returns an iterator over all query items.
for_each[_mut],
par_iter[_mut]
Runs a specified function for each query item.
iter_many[_mut]Iterates or runs a specified function over query items generated by a list of entities.
iter_combinations[_mut]Returns an iterator over all combinations of a specified number of query items.
get[_mut]Returns the query item for the specified entity.
many[_mut],
get_many[_mut]
Returns the query items for the specified entities.
single[_mut],
get_single[_mut]
Returns the query item while verifying that there aren’t others.

There are two methods for each type of query operation: immutable and mutable (ending with _mut). When using immutable methods, the query items returned are of type ROQueryItem, a read-only version of the query item. In this circumstance, every mutable reference in the query fetch type parameter is substituted by a shared reference.

§Performance

Creating a Query is a low-cost constant operation. Iterating it, on the other hand, fetches data from the world and generates items, which can have a significant computational cost.

Table component storage type is much more optimized for query iteration than SparseSet.

Two systems cannot be executed in parallel if both access the same component type where at least one of the accesses is mutable. This happens unless the executor can verify that no entity could be found in both queries.

Optional components increase the number of entities a query has to match against. This can hurt iteration performance, especially if the query solely consists of only optional components, since the query would iterate over each entity in the world.

The following table compares the computational complexity of the various methods and operations, where:

  • n is the number of entities that match the query,
  • r is the number of elements in a combination,
  • k is the number of involved entities in the operation,
  • a is the number of archetypes in the world,
  • C is the binomial coefficient, used to count combinations. nCr is read as “n choose r” and is equivalent to the number of distinct unordered subsets of r elements that can be taken from a set of n elements.
Query operationComputational complexity
iter[_mut]O(n)
for_each[_mut],
par_iter[_mut]
O(n)
iter_many[_mut]O(k)
iter_combinations[_mut]O(nCr)
get[_mut]O(1)
(get_)manyO(k)
(get_)many_mutO(k2)
single[_mut],
get_single[_mut]
O(a)
Archetype based filtering (With, Without, Or)O(a)
Change detection filtering (Added, Changed)O(a + n)

for_each methods are seen to be generally faster than their iter version on worlds with high archetype fragmentation. As iterators are in general more flexible and better integrated with the rest of the Rust ecosystem, it is advised to use iter methods over for_each. It is strongly advised to only use for_each if it tangibly improves performance: be sure profile or benchmark both before and after the change.

Implementations§

source§

impl<'w, 's, D, F> Query<'w, 's, D, F>
where D: QueryData, F: QueryFilter,

source

pub fn to_readonly(&self) -> Query<'_, 's, <D as QueryData>::ReadOnly, F>

Returns another Query from this that fetches the read-only version of the query items.

For example, Query<(&mut D1, &D2, &mut D3), With<F>> will become Query<(&D1, &D2, &D3), With<F>>. This can be useful when working around the borrow checker, or reusing functionality between systems via functions that accept query types.

source

pub fn iter(&self) -> QueryIter<'_, 's, <D as QueryData>::ReadOnly, F>

Returns an Iterator over the read-only query items.

§Example

Here, the report_names_system iterates over the Player component of every entity that contains it:

fn report_names_system(query: Query<&Player>) {
    for player in &query {
        println!("Say hello to {}!", player.name);
    }
}
§See also
Examples found in repository?
examples/ecs/system_param.rs (line 31)
30
31
32
    fn count(&mut self) {
        self.count.0 = self.players.iter().len();
    }
More examples
Hide additional examples
examples/ecs/one_shot_systems.rs (line 26)
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
fn count_entities(all_entities: Query<()>) {
    dbg!(all_entities.iter().count());
}

#[derive(Component)]
struct Callback(SystemId);

#[derive(Component)]
struct Triggered;

fn setup(world: &mut World) {
    let button_pressed_id = world.register_system(button_pressed);
    world.spawn((Callback(button_pressed_id), Triggered));
    // This entity does not have a Triggered component, so its callback won't run.
    let slider_toggled_id = world.register_system(slider_toggled);
    world.spawn(Callback(slider_toggled_id));
    world.run_system_once(count_entities);
}

fn button_pressed() {
    println!("A button was pressed!");
}

fn slider_toggled() {
    println!("A slider was toggled!");
}

/// Runs the systems associated with each `Callback` component if the entity also has a Triggered component.
///
/// This could be done in an exclusive system rather than using `Commands` if preferred.
fn evaluate_callbacks(query: Query<&Callback, With<Triggered>>, mut commands: Commands) {
    for callback in query.iter() {
        commands.run_system(callback.0);
    }
}
examples/stress_tests/many_animated_sprites.rs (line 149)
145
146
147
148
149
150
151
fn print_sprite_count(time: Res<Time>, mut timer: Local<PrintingTimer>, sprites: Query<&Sprite>) {
    timer.tick(time.delta());

    if timer.just_finished() {
        info!("Sprites: {}", sprites.iter().count());
    }
}
examples/stress_tests/many_sprites.rs (line 128)
124
125
126
127
128
129
130
fn print_sprite_count(time: Res<Time>, mut timer: Local<PrintingTimer>, sprites: Query<&Sprite>) {
    timer.tick(time.delta());

    if timer.just_finished() {
        info!("Sprites: {}", sprites.iter().count());
    }
}
examples/stress_tests/many_lights.rs (line 147)
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
fn print_light_count(time: Res<Time>, mut timer: Local<PrintingTimer>, lights: Query<&PointLight>) {
    timer.0.tick(time.delta());

    if timer.0.just_finished() {
        info!("Lights: {}", lights.iter().len());
    }
}

struct LogVisibleLights;

impl Plugin for LogVisibleLights {
    fn build(&self, app: &mut App) {
        let Ok(render_app) = app.get_sub_app_mut(RenderApp) else {
            return;
        };

        render_app.add_systems(Render, print_visible_light_count.in_set(RenderSet::Prepare));
    }
}

// System for printing the number of meshes on every tick of the timer
fn print_visible_light_count(
    time: Res<Time>,
    mut timer: Local<PrintingTimer>,
    visible: Query<&ExtractedPointLight>,
    global_light_meta: Res<GlobalLightMeta>,
) {
    timer.0.tick(time.delta());

    if timer.0.just_finished() {
        info!(
            "Visible Lights: {}, Rendered Lights: {}",
            visible.iter().len(),
            global_light_meta.entity_to_index.len()
        );
    }
}
examples/ecs/removal_detection.rs (line 47)
40
41
42
43
44
45
46
47
48
49
50
51
fn remove_component(
    time: Res<Time>,
    mut commands: Commands,
    query: Query<Entity, With<MyComponent>>,
) {
    // After two seconds have passed the `Component` is removed.
    if time.elapsed_seconds() > 2.0 {
        if let Some(entity) = query.iter().next() {
            commands.entity(entity).remove::<MyComponent>();
        }
    }
}
source

pub fn iter_mut(&mut self) -> QueryIter<'_, 's, D, F>

Returns an Iterator over the query items.

§Example

Here, the gravity_system updates the Velocity component of every entity that contains it:

fn gravity_system(mut query: Query<&mut Velocity>) {
    const DELTA: f32 = 1.0 / 60.0;
    for mut velocity in &mut query {
        velocity.y -= 9.8 * DELTA;
    }
}
§See also
  • iter for read-only query items.
  • for_each_mut for the closure based alternative.
Examples found in repository?
examples/2d/bounding_2d.rs (line 36)
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
fn spin(time: Res<Time>, mut query: Query<&mut Transform, With<Spin>>) {
    for mut transform in query.iter_mut() {
        transform.rotation *= Quat::from_rotation_z(time.delta_seconds() / 5.);
    }
}

#[derive(States, Default, Debug, Hash, PartialEq, Eq, Clone, Copy)]
enum Test {
    AabbSweep,
    CircleSweep,
    #[default]
    RayCast,
    AabbCast,
    CircleCast,
}

fn update_test_state(
    keycode: Res<ButtonInput<KeyCode>>,
    cur_state: Res<State<Test>>,
    mut state: ResMut<NextState<Test>>,
) {
    if !keycode.just_pressed(KeyCode::Space) {
        return;
    }

    use Test::*;
    let next = match **cur_state {
        AabbSweep => CircleSweep,
        CircleSweep => RayCast,
        RayCast => AabbCast,
        AabbCast => CircleCast,
        CircleCast => AabbSweep,
    };
    state.set(next);
}

fn update_text(mut text: Query<&mut Text>, cur_state: Res<State<Test>>) {
    if !cur_state.is_changed() {
        return;
    }

    let mut text = text.single_mut();
    let text = &mut text.sections[0].value;
    text.clear();

    text.push_str("Intersection test:\n");
    use Test::*;
    for &test in &[AabbSweep, CircleSweep, RayCast, AabbCast, CircleCast] {
        let s = if **cur_state == test { "*" } else { " " };
        text.push_str(&format!(" {s} {test:?} {s}\n"));
    }
    text.push_str("\npress Space to cycle");
}

#[derive(Component)]
enum Shape {
    Rectangle(Rectangle),
    Circle(Circle),
    Triangle(Triangle2d),
    Line(Segment2d),
    Capsule(Capsule2d),
    Polygon(RegularPolygon),
}

fn render_shapes(mut gizmos: Gizmos, query: Query<(&Shape, &Transform)>) {
    let color = Color::GRAY;
    for (shape, transform) in query.iter() {
        let translation = transform.translation.xy();
        let rotation = transform.rotation.to_euler(EulerRot::YXZ).2;
        match shape {
            Shape::Rectangle(r) => {
                gizmos.primitive_2d(*r, translation, rotation, color);
            }
            Shape::Circle(c) => {
                gizmos.primitive_2d(*c, translation, rotation, color);
            }
            Shape::Triangle(t) => {
                gizmos.primitive_2d(*t, translation, rotation, color);
            }
            Shape::Line(l) => {
                gizmos.primitive_2d(*l, translation, rotation, color);
            }
            Shape::Capsule(c) => {
                gizmos.primitive_2d(*c, translation, rotation, color);
            }
            Shape::Polygon(p) => {
                gizmos.primitive_2d(*p, translation, rotation, color);
            }
        }
    }
}

#[derive(Component)]
enum DesiredVolume {
    Aabb,
    Circle,
}

#[derive(Component, Debug)]
enum CurrentVolume {
    Aabb(Aabb2d),
    Circle(BoundingCircle),
}

fn update_volumes(
    mut commands: Commands,
    query: Query<
        (Entity, &DesiredVolume, &Shape, &Transform),
        Or<(Changed<DesiredVolume>, Changed<Shape>, Changed<Transform>)>,
    >,
) {
    for (entity, desired_volume, shape, transform) in query.iter() {
        let translation = transform.translation.xy();
        let rotation = transform.rotation.to_euler(EulerRot::YXZ).2;
        match desired_volume {
            DesiredVolume::Aabb => {
                let aabb = match shape {
                    Shape::Rectangle(r) => r.aabb_2d(translation, rotation),
                    Shape::Circle(c) => c.aabb_2d(translation, rotation),
                    Shape::Triangle(t) => t.aabb_2d(translation, rotation),
                    Shape::Line(l) => l.aabb_2d(translation, rotation),
                    Shape::Capsule(c) => c.aabb_2d(translation, rotation),
                    Shape::Polygon(p) => p.aabb_2d(translation, rotation),
                };
                commands.entity(entity).insert(CurrentVolume::Aabb(aabb));
            }
            DesiredVolume::Circle => {
                let circle = match shape {
                    Shape::Rectangle(r) => r.bounding_circle(translation, rotation),
                    Shape::Circle(c) => c.bounding_circle(translation, rotation),
                    Shape::Triangle(t) => t.bounding_circle(translation, rotation),
                    Shape::Line(l) => l.bounding_circle(translation, rotation),
                    Shape::Capsule(c) => c.bounding_circle(translation, rotation),
                    Shape::Polygon(p) => p.bounding_circle(translation, rotation),
                };
                commands
                    .entity(entity)
                    .insert(CurrentVolume::Circle(circle));
            }
        }
    }
}

fn render_volumes(mut gizmos: Gizmos, query: Query<(&CurrentVolume, &Intersects)>) {
    for (volume, intersects) in query.iter() {
        let color = if **intersects {
            Color::CYAN
        } else {
            Color::ORANGE_RED
        };
        match volume {
            CurrentVolume::Aabb(a) => {
                gizmos.rect_2d(a.center(), 0., a.half_size() * 2., color);
            }
            CurrentVolume::Circle(c) => {
                gizmos.circle_2d(c.center(), c.radius(), color);
            }
        }
    }
}

#[derive(Component, Deref, DerefMut, Default)]
struct Intersects(bool);

const OFFSET_X: f32 = 125.;
const OFFSET_Y: f32 = 75.;

fn setup(mut commands: Commands, loader: Res<AssetServer>) {
    commands.spawn(Camera2dBundle::default());
    commands.spawn((
        SpatialBundle {
            transform: Transform::from_xyz(-OFFSET_X, OFFSET_Y, 0.),
            ..default()
        },
        Shape::Circle(Circle::new(45.)),
        DesiredVolume::Aabb,
        Intersects::default(),
    ));

    commands.spawn((
        SpatialBundle {
            transform: Transform::from_xyz(0., OFFSET_Y, 0.),
            ..default()
        },
        Shape::Rectangle(Rectangle::new(80., 80.)),
        Spin,
        DesiredVolume::Circle,
        Intersects::default(),
    ));

    commands.spawn((
        SpatialBundle {
            transform: Transform::from_xyz(OFFSET_X, OFFSET_Y, 0.),
            ..default()
        },
        Shape::Triangle(Triangle2d::new(
            Vec2::new(-40., -40.),
            Vec2::new(-20., 40.),
            Vec2::new(40., 50.),
        )),
        Spin,
        DesiredVolume::Aabb,
        Intersects::default(),
    ));

    commands.spawn((
        SpatialBundle {
            transform: Transform::from_xyz(-OFFSET_X, -OFFSET_Y, 0.),
            ..default()
        },
        Shape::Line(Segment2d::new(Direction2d::from_xy(1., 0.3).unwrap(), 90.)),
        Spin,
        DesiredVolume::Circle,
        Intersects::default(),
    ));

    commands.spawn((
        SpatialBundle {
            transform: Transform::from_xyz(0., -OFFSET_Y, 0.),
            ..default()
        },
        Shape::Capsule(Capsule2d::new(25., 50.)),
        Spin,
        DesiredVolume::Aabb,
        Intersects::default(),
    ));

    commands.spawn((
        SpatialBundle {
            transform: Transform::from_xyz(OFFSET_X, -OFFSET_Y, 0.),
            ..default()
        },
        Shape::Polygon(RegularPolygon::new(50., 6)),
        Spin,
        DesiredVolume::Circle,
        Intersects::default(),
    ));

    commands.spawn(
        TextBundle::from_section(
            "",
            TextStyle {
                font: loader.load("fonts/FiraMono-Medium.ttf"),
                font_size: 26.0,
                ..default()
            },
        )
        .with_style(Style {
            position_type: PositionType::Absolute,
            bottom: Val::Px(10.0),
            left: Val::Px(10.0),
            ..default()
        }),
    );
}

fn draw_ray(gizmos: &mut Gizmos, ray: &RayCast2d) {
    gizmos.line_2d(
        ray.ray.origin,
        ray.ray.origin + *ray.ray.direction * ray.max,
        Color::WHITE,
    );
    for r in [1., 2., 3.] {
        gizmos.circle_2d(ray.ray.origin, r, Color::FUCHSIA);
    }
}

fn get_and_draw_ray(gizmos: &mut Gizmos, time: &Time) -> RayCast2d {
    let ray = Vec2::new(time.elapsed_seconds().cos(), time.elapsed_seconds().sin());
    let dist = 150. + (0.5 * time.elapsed_seconds()).sin().abs() * 500.;

    let aabb_ray = Ray2d {
        origin: ray * 250.,
        direction: Direction2d::new_unchecked(-ray),
    };
    let ray_cast = RayCast2d::from_ray(aabb_ray, dist - 20.);

    draw_ray(gizmos, &ray_cast);
    ray_cast
}

fn ray_cast_system(
    mut gizmos: Gizmos,
    time: Res<Time>,
    mut volumes: Query<(&CurrentVolume, &mut Intersects)>,
) {
    let ray_cast = get_and_draw_ray(&mut gizmos, &time);

    for (volume, mut intersects) in volumes.iter_mut() {
        let toi = match volume {
            CurrentVolume::Aabb(a) => ray_cast.aabb_intersection_at(a),
            CurrentVolume::Circle(c) => ray_cast.circle_intersection_at(c),
        };
        **intersects = toi.is_some();
        if let Some(toi) = toi {
            for r in [1., 2., 3.] {
                gizmos.circle_2d(
                    ray_cast.ray.origin + *ray_cast.ray.direction * toi,
                    r,
                    Color::GREEN,
                );
            }
        }
    }
}

fn aabb_cast_system(
    mut gizmos: Gizmos,
    time: Res<Time>,
    mut volumes: Query<(&CurrentVolume, &mut Intersects)>,
) {
    let ray_cast = get_and_draw_ray(&mut gizmos, &time);
    let aabb_cast = AabbCast2d {
        aabb: Aabb2d::new(Vec2::ZERO, Vec2::splat(15.)),
        ray: ray_cast,
    };

    for (volume, mut intersects) in volumes.iter_mut() {
        let toi = match *volume {
            CurrentVolume::Aabb(a) => aabb_cast.aabb_collision_at(a),
            CurrentVolume::Circle(_) => None,
        };

        **intersects = toi.is_some();
        if let Some(toi) = toi {
            gizmos.rect_2d(
                aabb_cast.ray.ray.origin
                    + *aabb_cast.ray.ray.direction * toi
                    + aabb_cast.aabb.center(),
                0.,
                aabb_cast.aabb.half_size() * 2.,
                Color::GREEN,
            );
        }
    }
}

fn bounding_circle_cast_system(
    mut gizmos: Gizmos,
    time: Res<Time>,
    mut volumes: Query<(&CurrentVolume, &mut Intersects)>,
) {
    let ray_cast = get_and_draw_ray(&mut gizmos, &time);
    let circle_cast = BoundingCircleCast {
        circle: BoundingCircle::new(Vec2::ZERO, 15.),
        ray: ray_cast,
    };

    for (volume, mut intersects) in volumes.iter_mut() {
        let toi = match *volume {
            CurrentVolume::Aabb(_) => None,
            CurrentVolume::Circle(c) => circle_cast.circle_collision_at(c),
        };

        **intersects = toi.is_some();
        if let Some(toi) = toi {
            gizmos.circle_2d(
                circle_cast.ray.ray.origin
                    + *circle_cast.ray.ray.direction * toi
                    + circle_cast.circle.center(),
                circle_cast.circle.radius(),
                Color::GREEN,
            );
        }
    }
}

fn get_intersection_position(time: &Time) -> Vec2 {
    let x = (0.8 * time.elapsed_seconds()).cos() * 250.;
    let y = (0.4 * time.elapsed_seconds()).sin() * 100.;
    Vec2::new(x, y)
}

fn aabb_intersection_system(
    mut gizmos: Gizmos,
    time: Res<Time>,
    mut volumes: Query<(&CurrentVolume, &mut Intersects)>,
) {
    let center = get_intersection_position(&time);
    let aabb = Aabb2d::new(center, Vec2::splat(50.));
    gizmos.rect_2d(center, 0., aabb.half_size() * 2., Color::YELLOW);

    for (volume, mut intersects) in volumes.iter_mut() {
        let hit = match volume {
            CurrentVolume::Aabb(a) => aabb.intersects(a),
            CurrentVolume::Circle(c) => aabb.intersects(c),
        };

        **intersects = hit;
    }
}

fn circle_intersection_system(
    mut gizmos: Gizmos,
    time: Res<Time>,
    mut volumes: Query<(&CurrentVolume, &mut Intersects)>,
) {
    let center = get_intersection_position(&time);
    let circle = BoundingCircle::new(center, 50.);
    gizmos.circle_2d(center, circle.radius(), Color::YELLOW);

    for (volume, mut intersects) in volumes.iter_mut() {
        let hit = match volume {
            CurrentVolume::Aabb(a) => circle.intersects(a),
            CurrentVolume::Circle(c) => circle.intersects(c),
        };

        **intersects = hit;
    }
}
More examples
Hide additional examples
examples/3d/irradiance_volumes.rs (line 321)
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
fn update_text(
    mut text_query: Query<&mut Text>,
    app_status: Res<AppStatus>,
    asset_server: Res<AssetServer>,
) {
    for mut text in text_query.iter_mut() {
        *text = app_status.create_text(&asset_server);
    }
}

impl AppStatus {
    // Constructs the help text at the bottom of the screen based on the
    // application status.
    fn create_text(&self, asset_server: &AssetServer) -> Text {
        let irradiance_volume_help_text = if self.irradiance_volume_present {
            DISABLE_IRRADIANCE_VOLUME_HELP_TEXT
        } else {
            ENABLE_IRRADIANCE_VOLUME_HELP_TEXT
        };

        let voxels_help_text = if self.voxels_visible {
            HIDE_VOXELS_HELP_TEXT
        } else {
            SHOW_VOXELS_HELP_TEXT
        };

        let rotation_help_text = if self.rotating {
            STOP_ROTATION_HELP_TEXT
        } else {
            START_ROTATION_HELP_TEXT
        };

        let switch_mesh_help_text = match self.model {
            ExampleModel::Sphere => SWITCH_TO_FOX_HELP_TEXT,
            ExampleModel::Fox => SWITCH_TO_SPHERE_HELP_TEXT,
        };

        Text::from_section(
            format!(
                "{}\n{}\n{}\n{}\n{}",
                CLICK_TO_MOVE_HELP_TEXT,
                voxels_help_text,
                irradiance_volume_help_text,
                rotation_help_text,
                switch_mesh_help_text
            ),
            TextStyle {
                font: asset_server.load("fonts/FiraMono-Medium.ttf"),
                font_size: 24.0,
                color: Color::ANTIQUE_WHITE,
            },
        )
    }
}

// Rotates the camera a bit every frame.
fn rotate_camera(
    mut camera_query: Query<&mut Transform, With<Camera3d>>,
    time: Res<Time>,
    app_status: Res<AppStatus>,
) {
    if !app_status.rotating {
        return;
    }

    for mut transform in camera_query.iter_mut() {
        transform.translation = Vec2::from_angle(ROTATION_SPEED * time.delta_seconds())
            .rotate(transform.translation.xz())
            .extend(transform.translation.y)
            .xzy();
        transform.look_at(Vec3::ZERO, Vec3::Y);
    }
}

// Toggles between the unskinned sphere model and the skinned fox model if the
// user requests it.
fn change_main_object(
    keyboard: Res<ButtonInput<KeyCode>>,
    mut app_status: ResMut<AppStatus>,
    mut sphere_query: Query<
        &mut Visibility,
        (With<MainObject>, With<Handle<Mesh>>, Without<Handle<Scene>>),
    >,
    mut fox_query: Query<&mut Visibility, (With<MainObject>, With<Handle<Scene>>)>,
) {
    if !keyboard.just_pressed(KeyCode::Tab) {
        return;
    }
    let Some(mut sphere_visibility) = sphere_query.iter_mut().next() else {
        return;
    };
    let Some(mut fox_visibility) = fox_query.iter_mut().next() else {
        return;
    };

    match app_status.model {
        ExampleModel::Sphere => {
            *sphere_visibility = Visibility::Hidden;
            *fox_visibility = Visibility::Visible;
            app_status.model = ExampleModel::Fox;
        }
        ExampleModel::Fox => {
            *sphere_visibility = Visibility::Visible;
            *fox_visibility = Visibility::Hidden;
            app_status.model = ExampleModel::Sphere;
        }
    }
}

impl Default for AppStatus {
    fn default() -> Self {
        Self {
            irradiance_volume_present: true,
            rotating: true,
            model: ExampleModel::Sphere,
            voxels_visible: false,
        }
    }
}

// Turns on and off the irradiance volume as requested by the user.
fn toggle_irradiance_volumes(
    mut commands: Commands,
    keyboard: Res<ButtonInput<KeyCode>>,
    light_probe_query: Query<Entity, With<LightProbe>>,
    mut app_status: ResMut<AppStatus>,
    assets: Res<ExampleAssets>,
    mut ambient_light: ResMut<AmbientLight>,
) {
    if !keyboard.just_pressed(KeyCode::Space) {
        return;
    };

    let Some(light_probe) = light_probe_query.iter().next() else {
        return;
    };

    if app_status.irradiance_volume_present {
        commands.entity(light_probe).remove::<IrradianceVolume>();
        ambient_light.brightness = AMBIENT_LIGHT_BRIGHTNESS * IRRADIANCE_VOLUME_INTENSITY;
        app_status.irradiance_volume_present = false;
    } else {
        commands.entity(light_probe).insert(IrradianceVolume {
            voxels: assets.irradiance_volume.clone(),
            intensity: IRRADIANCE_VOLUME_INTENSITY,
        });
        ambient_light.brightness = 0.0;
        app_status.irradiance_volume_present = true;
    }
}

fn toggle_rotation(keyboard: Res<ButtonInput<KeyCode>>, mut app_status: ResMut<AppStatus>) {
    if keyboard.just_pressed(KeyCode::Enter) {
        app_status.rotating = !app_status.rotating;
    }
}

// Handles clicks on the plane that reposition the object.
fn handle_mouse_clicks(
    buttons: Res<ButtonInput<MouseButton>>,
    windows: Query<&Window, With<PrimaryWindow>>,
    cameras: Query<(&Camera, &GlobalTransform)>,
    mut main_objects: Query<&mut Transform, With<MainObject>>,
) {
    if !buttons.pressed(MouseButton::Left) {
        return;
    }
    let Some(mouse_position) = windows
        .iter()
        .next()
        .and_then(|window| window.cursor_position())
    else {
        return;
    };
    let Some((camera, camera_transform)) = cameras.iter().next() else {
        return;
    };

    // Figure out where the user clicked on the plane.
    let Some(ray) = camera.viewport_to_world(camera_transform, mouse_position) else {
        return;
    };
    let Some(ray_distance) = ray.intersect_plane(Vec3::ZERO, Plane3d::new(Vec3::Y)) else {
        return;
    };
    let plane_intersection = ray.origin + ray.direction.normalize() * ray_distance;

    // Move all the main objeccts.
    for mut transform in main_objects.iter_mut() {
        transform.translation = vec3(
            plane_intersection.x,
            transform.translation.y,
            plane_intersection.z,
        );
    }
}

impl FromWorld for ExampleAssets {
    fn from_world(world: &mut World) -> Self {
        // Load all the assets.
        let asset_server = world.resource::<AssetServer>();
        let fox = asset_server.load("models/animated/Fox.glb#Scene0");
        let main_scene =
            asset_server.load("models/IrradianceVolumeExample/IrradianceVolumeExample.glb#Scene0");
        let irradiance_volume = asset_server.load::<Image>("irradiance_volumes/Example.vxgi.ktx2");
        let fox_animation =
            asset_server.load::<AnimationClip>("models/animated/Fox.glb#Animation1");

        // Just use a specular map for the skybox since it's not too blurry.
        // In reality you wouldn't do this--you'd use a real skybox texture--but
        // reusing the textures like this saves space in the Bevy repository.
        let skybox = asset_server.load::<Image>("environment_maps/pisa_specular_rgb9e5_zstd.ktx2");

        let mut mesh_assets = world.resource_mut::<Assets<Mesh>>();
        let main_sphere = mesh_assets.add(Sphere::default().mesh().uv(32, 18));
        let voxel_cube = mesh_assets.add(Cuboid::default());

        let mut standard_material_assets = world.resource_mut::<Assets<StandardMaterial>>();
        let main_material = standard_material_assets.add(Color::SILVER);

        ExampleAssets {
            main_sphere,
            fox,
            main_sphere_material: main_material,
            main_scene,
            irradiance_volume,
            fox_animation,
            voxel_cube,
            skybox,
        }
    }
}

// Plays the animation on the fox.
fn play_animations(assets: Res<ExampleAssets>, mut players: Query<&mut AnimationPlayer>) {
    for mut player in players.iter_mut() {
        // This will safely do nothing if the animation is already playing.
        player.play(assets.fox_animation.clone()).repeat();
    }
}

fn create_cubes(
    image_assets: Res<Assets<Image>>,
    mut commands: Commands,
    irradiance_volumes: Query<(&IrradianceVolume, &GlobalTransform)>,
    voxel_cube_parents: Query<Entity, With<VoxelCubeParent>>,
    voxel_cubes: Query<Entity, With<VoxelCube>>,
    example_assets: Res<ExampleAssets>,
    mut voxel_visualization_material_assets: ResMut<Assets<VoxelVisualizationMaterial>>,
) {
    // If voxel cubes have already been spawned, don't do anything.
    if !voxel_cubes.is_empty() {
        return;
    }

    let Some(voxel_cube_parent) = voxel_cube_parents.iter().next() else {
        return;
    };

    for (irradiance_volume, global_transform) in irradiance_volumes.iter() {
        let Some(image) = image_assets.get(&irradiance_volume.voxels) else {
            continue;
        };

        let resolution = image.texture_descriptor.size;

        let voxel_cube_material = voxel_visualization_material_assets.add(ExtendedMaterial {
            base: StandardMaterial::from(Color::RED),
            extension: VoxelVisualizationExtension {
                irradiance_volume_info: VoxelVisualizationIrradianceVolumeInfo {
                    transform: VOXEL_TRANSFORM.inverse(),
                    inverse_transform: VOXEL_TRANSFORM,
                    resolution: uvec3(
                        resolution.width,
                        resolution.height,
                        resolution.depth_or_array_layers,
                    ),
                    intensity: IRRADIANCE_VOLUME_INTENSITY,
                },
            },
        });

        let scale = vec3(
            1.0 / resolution.width as f32,
            1.0 / resolution.height as f32,
            1.0 / resolution.depth_or_array_layers as f32,
        );

        // Spawn a cube for each voxel.
        for z in 0..resolution.depth_or_array_layers {
            for y in 0..resolution.height {
                for x in 0..resolution.width {
                    let uvw = (uvec3(x, y, z).as_vec3() + 0.5) * scale - 0.5;
                    let pos = global_transform.transform_point(uvw);
                    let voxel_cube = commands
                        .spawn(MaterialMeshBundle {
                            mesh: example_assets.voxel_cube.clone(),
                            material: voxel_cube_material.clone(),
                            transform: Transform::from_scale(Vec3::splat(VOXEL_CUBE_SCALE))
                                .with_translation(pos),
                            ..default()
                        })
                        .insert(VoxelCube)
                        .insert(NotShadowCaster)
                        .id();

                    commands.entity(voxel_cube_parent).add_child(voxel_cube);
                }
            }
        }
    }
}

// Draws a gizmo showing the bounds of the irradiance volume.
fn draw_gizmo(
    mut gizmos: Gizmos,
    irradiance_volume_query: Query<&GlobalTransform, With<IrradianceVolume>>,
    app_status: Res<AppStatus>,
) {
    if app_status.voxels_visible {
        for transform in irradiance_volume_query.iter() {
            gizmos.cuboid(*transform, GIZMO_COLOR);
        }
    }
}

// Handles a request from the user to toggle the voxel visibility on and off.
fn toggle_voxel_visibility(
    keyboard: Res<ButtonInput<KeyCode>>,
    mut app_status: ResMut<AppStatus>,
    mut voxel_cube_parent_query: Query<&mut Visibility, With<VoxelCubeParent>>,
) {
    if !keyboard.just_pressed(KeyCode::Backspace) {
        return;
    }

    app_status.voxels_visible = !app_status.voxels_visible;

    for mut visibility in voxel_cube_parent_query.iter_mut() {
        *visibility = if app_status.voxels_visible {
            Visibility::Visible
        } else {
            Visibility::Hidden
        };
    }
}
examples/3d/reflection_probes.rs (line 249)
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
fn update_text(
    mut text_query: Query<&mut Text>,
    app_status: Res<AppStatus>,
    asset_server: Res<AssetServer>,
) {
    for mut text in text_query.iter_mut() {
        *text = app_status.create_text(&asset_server);
    }
}

impl TryFrom<u32> for ReflectionMode {
    type Error = ();

    fn try_from(value: u32) -> Result<Self, Self::Error> {
        match value {
            0 => Ok(ReflectionMode::None),
            1 => Ok(ReflectionMode::EnvironmentMap),
            2 => Ok(ReflectionMode::ReflectionProbe),
            _ => Err(()),
        }
    }
}

impl Display for ReflectionMode {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
        let text = match *self {
            ReflectionMode::None => "No reflections",
            ReflectionMode::EnvironmentMap => "Environment map",
            ReflectionMode::ReflectionProbe => "Reflection probe",
        };
        formatter.write_str(text)
    }
}

impl AppStatus {
    // Constructs the help text at the bottom of the screen based on the
    // application status.
    fn create_text(&self, asset_server: &AssetServer) -> Text {
        let rotation_help_text = if self.rotating {
            STOP_ROTATION_HELP_TEXT
        } else {
            START_ROTATION_HELP_TEXT
        };

        Text::from_section(
            format!(
                "{}\n{}\n{}",
                self.reflection_mode, rotation_help_text, REFLECTION_MODE_HELP_TEXT
            ),
            TextStyle {
                font: asset_server.load("fonts/FiraMono-Medium.ttf"),
                font_size: 24.0,
                color: Color::ANTIQUE_WHITE,
            },
        )
    }
}

// Creates the world environment map light, used as a fallback if no reflection
// probe is applicable to a mesh.
fn create_camera_environment_map_light(cubemaps: &Cubemaps) -> EnvironmentMapLight {
    EnvironmentMapLight {
        diffuse_map: cubemaps.diffuse.clone(),
        specular_map: cubemaps.specular_environment_map.clone(),
        intensity: 5000.0,
    }
}

// Rotates the camera a bit every frame.
fn rotate_camera(
    mut camera_query: Query<&mut Transform, With<Camera3d>>,
    app_status: Res<AppStatus>,
) {
    if !app_status.rotating {
        return;
    }

    for mut transform in camera_query.iter_mut() {
        transform.translation = Vec2::from_angle(ROTATION_SPEED)
            .rotate(transform.translation.xz())
            .extend(transform.translation.y)
            .xzy();
        transform.look_at(Vec3::ZERO, Vec3::Y);
    }
}
examples/stress_tests/text_pipeline.rs (line 76)
74
75
76
77
78
79
fn update_text_bounds(time: Res<Time>, mut text_bounds_query: Query<&mut Text2dBounds>) {
    let width = (1. + time.elapsed_seconds().sin()) * 600.0;
    for mut text_bounds in text_bounds_query.iter_mut() {
        text_bounds.size.x = width;
    }
}
examples/shader/shader_prepass.rs (line 190)
189
190
191
192
193
194
fn rotate(mut q: Query<&mut Transform, With<Rotates>>, time: Res<Time>) {
    for mut t in q.iter_mut() {
        let rot = (time.elapsed_seconds().sin() * 0.5 + 0.5) * std::f32::consts::PI * 2.0;
        t.rotation = Quat::from_rotation_z(rot);
    }
}
examples/3d/bloom_3d.rs (line 234)
233
234
235
236
237
238
fn bounce_spheres(time: Res<Time>, mut query: Query<&mut Transform, With<Bouncing>>) {
    for mut transform in query.iter_mut() {
        transform.translation.y =
            (transform.translation.x + transform.translation.z + time.elapsed_seconds()).sin();
    }
}
source

pub fn iter_combinations<const K: usize>( &self ) -> QueryCombinationIter<'_, 's, <D as QueryData>::ReadOnly, F, K>

Returns a QueryCombinationIter over all combinations of K read-only query items without repetition.

§Example
fn some_system(query: Query<&ComponentA>) {
    for [a1, a2] in query.iter_combinations() {
        // ...
    }
}
§See also
source

pub fn iter_combinations_mut<const K: usize>( &mut self ) -> QueryCombinationIter<'_, 's, D, F, K>

Returns a QueryCombinationIter over all combinations of K query items without repetition.

§Example
fn some_system(mut query: Query<&mut ComponentA>) {
    let mut combinations = query.iter_combinations_mut();
    while let Some([mut a1, mut a2]) = combinations.fetch_next() {
        // mutably access components data
    }
}
§See also
Examples found in repository?
examples/ecs/iter_combinations.rs (line 127)
126
127
128
129
130
131
132
133
134
135
136
137
138
139
fn interact_bodies(mut query: Query<(&Mass, &GlobalTransform, &mut Acceleration)>) {
    let mut iter = query.iter_combinations_mut();
    while let Some([(Mass(m1), transform1, mut acc1), (Mass(m2), transform2, mut acc2)]) =
        iter.fetch_next()
    {
        let delta = transform2.translation() - transform1.translation();
        let distance_sq: f32 = delta.length_squared();

        let f = GRAVITY_CONSTANT / distance_sq;
        let force_unit_mass = delta * f;
        acc1.0 += force_unit_mass * *m2;
        acc2.0 -= force_unit_mass * *m1;
    }
}
source

pub fn iter_many<EntityList>( &self, entities: EntityList ) -> QueryManyIter<'_, 's, <D as QueryData>::ReadOnly, F, <EntityList as IntoIterator>::IntoIter>
where EntityList: IntoIterator, <EntityList as IntoIterator>::Item: Borrow<Entity>,

Returns an Iterator over the read-only query items generated from an Entity list.

Items are returned in the order of the list of entities. Entities that don’t match the query are skipped.

§Example
// A component containing an entity list.
#[derive(Component)]
struct Friends {
    list: Vec<Entity>,
}

fn system(
    friends_query: Query<&Friends>,
    counter_query: Query<&Counter>,
) {
    for friends in &friends_query {
        for counter in counter_query.iter_many(&friends.list) {
            println!("Friend's counter: {:?}", counter.value);
        }
    }
}
§See also
source

pub fn iter_many_mut<EntityList>( &mut self, entities: EntityList ) -> QueryManyIter<'_, 's, D, F, <EntityList as IntoIterator>::IntoIter>
where EntityList: IntoIterator, <EntityList as IntoIterator>::Item: Borrow<Entity>,

Returns an iterator over the query items generated from an Entity list.

Items are returned in the order of the list of entities. Entities that don’t match the query are skipped.

§Examples
#[derive(Component)]
struct Counter {
    value: i32
}

#[derive(Component)]
struct Friends {
    list: Vec<Entity>,
}

fn system(
    friends_query: Query<&Friends>,
    mut counter_query: Query<&mut Counter>,
) {
    for friends in &friends_query {
        let mut iter = counter_query.iter_many_mut(&friends.list);
        while let Some(mut counter) = iter.fetch_next() {
            println!("Friend's counter: {:?}", counter.value);
            counter.value += 1;
        }
    }
}
source

pub unsafe fn iter_unsafe(&self) -> QueryIter<'_, 's, D, F>

Returns an Iterator over the query items.

§Safety

This function makes it possible to violate Rust’s aliasing guarantees. You must make sure this call does not result in multiple mutable references to the same component.

§See also
source

pub unsafe fn iter_combinations_unsafe<const K: usize>( &self ) -> QueryCombinationIter<'_, 's, D, F, K>

Iterates over all possible combinations of K query items without repetition.

§Safety

This allows aliased mutability. You must make sure this call does not result in multiple mutable references to the same component.

§See also
source

pub unsafe fn iter_many_unsafe<EntityList>( &self, entities: EntityList ) -> QueryManyIter<'_, 's, D, F, <EntityList as IntoIterator>::IntoIter>
where EntityList: IntoIterator, <EntityList as IntoIterator>::Item: Borrow<Entity>,

Returns an Iterator over the query items generated from an Entity list.

§Safety

This allows aliased mutability and does not check for entity uniqueness. You must make sure this call does not result in multiple mutable references to the same component. Particular care must be taken when collecting the data (rather than iterating over it one item at a time) such as via Iterator::collect.

§See also
source

pub fn for_each<'this>( &'this self, f: impl FnMut(<<D as QueryData>::ReadOnly as WorldQuery>::Item<'this>) )

👎Deprecated since 0.13.0: Query::for_each was not idiomatic Rust and has been moved to query.iter().for_each()

Runs f on each read-only query item.

Shorthand for query.iter().for_each(..).

§Example

Here, the report_names_system iterates over the Player component of every entity that contains it:

fn report_names_system(query: Query<&Player>) {
    query.for_each(|player| {
        println!("Say hello to {}!", player.name);
    });
}
§See also
  • for_each_mut to operate on mutable query items.
  • iter for the iterator based alternative.
source

pub fn for_each_mut<'a>( &'a mut self, f: impl FnMut(<D as WorldQuery>::Item<'a>) )

👎Deprecated since 0.13.0: Query::for_each_mut was not idiomatic Rust and has been moved to query.iter_mut().for_each()

Runs f on each query item.

Shorthand for query.iter_mut().for_each(..).

§Example

Here, the gravity_system updates the Velocity component of every entity that contains it:

fn gravity_system(mut query: Query<&mut Velocity>) {
    const DELTA: f32 = 1.0 / 60.0;
    query.for_each_mut(|mut velocity| {
        velocity.y -= 9.8 * DELTA;
    });
}
§See also
  • for_each to operate on read-only query items.
  • iter_mut for the iterator based alternative.
source

pub fn par_iter(&self) -> QueryParIter<'_, '_, <D as QueryData>::ReadOnly, F>

Returns a parallel iterator over the query results for the given World.

This can only be called for read-only queries, see par_iter_mut for write-queries.

Note that you must use the for_each method to iterate over the results, see par_iter_mut for an example.

source

pub fn par_iter_mut(&mut self) -> QueryParIter<'_, '_, D, F>

Returns a parallel iterator over the query results for the given World.

This can only be called for mutable queries, see par_iter for read-only-queries.

§Example

Here, the gravity_system updates the Velocity component of every entity that contains it:

fn gravity_system(mut query: Query<&mut Velocity>) {
    const DELTA: f32 = 1.0 / 60.0;
    query.par_iter_mut().for_each(|mut velocity| {
        velocity.y -= 9.8 * DELTA;
    });
}
Examples found in repository?
examples/ecs/parallel_query.rs (line 37)
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
fn move_system(mut sprites: Query<(&mut Transform, &Velocity)>) {
    // Compute the new location of each sprite in parallel on the
    // ComputeTaskPool
    //
    // This example is only for demonstrative purposes. Using a
    // ParallelIterator for an inexpensive operation like addition on only 128
    // elements will not typically be faster than just using a normal Iterator.
    // See the ParallelIterator documentation for more information on when
    // to use or not use ParallelIterator over a normal Iterator.
    sprites
        .par_iter_mut()
        .for_each(|(mut transform, velocity)| {
            transform.translation += velocity.extend(0.0);
        });
}

// Bounce sprites outside the window
fn bounce_system(windows: Query<&Window>, mut sprites: Query<(&Transform, &mut Velocity)>) {
    let window = windows.single();
    let width = window.width();
    let height = window.height();
    let left = width / -2.0;
    let right = width / 2.0;
    let bottom = height / -2.0;
    let top = height / 2.0;
    // The default batch size can also be overridden.
    // In this case a batch size of 32 is chosen to limit the overhead of
    // ParallelIterator, since negating a vector is very inexpensive.
    sprites
        .par_iter_mut()
        .batching_strategy(BatchingStrategy::fixed(32))
        .for_each(|(transform, mut v)| {
            if !(left < transform.translation.x
                && transform.translation.x < right
                && bottom < transform.translation.y
                && transform.translation.y < top)
            {
                // For simplicity, just reverse the velocity; don't use realistic bounces
                v.0 = -v.0;
            }
        });
}
source

pub fn get( &self, entity: Entity ) -> Result<<<D as QueryData>::ReadOnly as WorldQuery>::Item<'_>, QueryEntityError>

Returns the read-only query item for the given Entity.

In case of a nonexisting entity or mismatched component, a QueryEntityError is returned instead.

§Example

Here, get is used to retrieve the exact query item of the entity specified by the SelectedCharacter resource.

fn print_selected_character_name_system(
       query: Query<&Character>,
       selection: Res<SelectedCharacter>
)
{
    if let Ok(selected_character) = query.get(selection.entity) {
        println!("{}", selected_character.name);
    }
}
§See also
  • get_mut to get a mutable query item.
Examples found in repository?
examples/ui/ui.rs (line 323)
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
fn mouse_scroll(
    mut mouse_wheel_events: EventReader<MouseWheel>,
    mut query_list: Query<(&mut ScrollingList, &mut Style, &Parent, &Node)>,
    query_node: Query<&Node>,
) {
    for mouse_wheel_event in mouse_wheel_events.read() {
        for (mut scrolling_list, mut style, parent, list_node) in &mut query_list {
            let items_height = list_node.size().y;
            let container_height = query_node.get(parent.get()).unwrap().size().y;

            let max_scroll = (items_height - container_height).max(0.);

            let dy = match mouse_wheel_event.unit {
                MouseScrollUnit::Line => mouse_wheel_event.y * 20.,
                MouseScrollUnit::Pixel => mouse_wheel_event.y,
            };

            scrolling_list.position += dy;
            scrolling_list.position = scrolling_list.position.clamp(-max_scroll, 0.);
            style.top = Val::Px(scrolling_list.position);
        }
    }
}
More examples
Hide additional examples
examples/animation/gltf_skinned_mesh.rs (line 58)
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
fn joint_animation(
    time: Res<Time>,
    parent_query: Query<&Parent, With<SkinnedMesh>>,
    children_query: Query<&Children>,
    mut transform_query: Query<&mut Transform>,
) {
    // Iter skinned mesh entity
    for skinned_mesh_parent in &parent_query {
        // Mesh node is the parent of the skinned mesh entity.
        let mesh_node_entity = skinned_mesh_parent.get();
        // Get `Children` in the mesh node.
        let mesh_node_children = children_query.get(mesh_node_entity).unwrap();

        // First joint is the second child of the mesh node.
        let first_joint_entity = mesh_node_children[1];
        // Get `Children` in the first joint.
        let first_joint_children = children_query.get(first_joint_entity).unwrap();

        // Second joint is the first child of the first joint.
        let second_joint_entity = first_joint_children[0];
        // Get `Transform` in the second joint.
        let mut second_joint_transform = transform_query.get_mut(second_joint_entity).unwrap();

        second_joint_transform.rotation =
            Quat::from_rotation_z(FRAC_PI_2 * time.elapsed_seconds().sin());
    }
}
examples/3d/split_screen.rs (line 205)
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
fn set_camera_viewports(
    windows: Query<&Window>,
    mut resize_events: EventReader<WindowResized>,
    mut left_camera: Query<&mut Camera, (With<LeftCamera>, Without<RightCamera>)>,
    mut right_camera: Query<&mut Camera, With<RightCamera>>,
) {
    // We need to dynamically resize the camera's viewports whenever the window size changes
    // so then each camera always takes up half the screen.
    // A resize_event is sent when the window is first created, allowing us to reuse this system for initial setup.
    for resize_event in resize_events.read() {
        let window = windows.get(resize_event.window).unwrap();
        let mut left_camera = left_camera.single_mut();
        left_camera.viewport = Some(Viewport {
            physical_position: UVec2::new(0, 0),
            physical_size: UVec2::new(
                window.resolution.physical_width() / 2,
                window.resolution.physical_height(),
            ),
            ..default()
        });

        let mut right_camera = right_camera.single_mut();
        right_camera.viewport = Some(Viewport {
            physical_position: UVec2::new(window.resolution.physical_width() / 2, 0),
            physical_size: UVec2::new(
                window.resolution.physical_width() / 2,
                window.resolution.physical_height(),
            ),
            ..default()
        });
    }
}
examples/games/alien_cake_addict.rs (line 270)
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
fn focus_camera(
    time: Res<Time>,
    mut game: ResMut<Game>,
    mut transforms: ParamSet<(Query<&mut Transform, With<Camera3d>>, Query<&Transform>)>,
) {
    const SPEED: f32 = 2.0;
    // if there is both a player and a bonus, target the mid-point of them
    if let (Some(player_entity), Some(bonus_entity)) = (game.player.entity, game.bonus.entity) {
        let transform_query = transforms.p1();
        if let (Ok(player_transform), Ok(bonus_transform)) = (
            transform_query.get(player_entity),
            transform_query.get(bonus_entity),
        ) {
            game.camera_should_focus = player_transform
                .translation
                .lerp(bonus_transform.translation, 0.5);
        }
        // otherwise, if there is only a player, target the player
    } else if let Some(player_entity) = game.player.entity {
        if let Ok(player_transform) = transforms.p1().get(player_entity) {
            game.camera_should_focus = player_transform.translation;
        }
        // otherwise, target the middle
    } else {
        game.camera_should_focus = Vec3::from(RESET_FOCUS);
    }
    // calculate the camera motion based on the difference between where the camera is looking
    // and where it should be looking; the greater the distance, the faster the motion;
    // smooth out the camera movement using the frame time
    let mut camera_motion = game.camera_should_focus - game.camera_is_focus;
    if camera_motion.length() > 0.2 {
        camera_motion *= SPEED * time.delta_seconds();
        // set the new camera's actual focus
        game.camera_is_focus += camera_motion;
    }
    // look at that new camera's actual focus
    for mut transform in transforms.p0().iter_mut() {
        *transform = transform.looking_at(game.camera_is_focus, Vec3::Y);
    }
}
examples/3d/blend_modes.rs (line 332)
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
fn example_control_system(
    mut materials: ResMut<Assets<StandardMaterial>>,
    controllable: Query<(&Handle<StandardMaterial>, &ExampleControls)>,
    mut camera: Query<(&mut Camera, &mut Transform, &GlobalTransform), With<Camera3d>>,
    mut labels: Query<(&mut Style, &ExampleLabel)>,
    mut display: Query<&mut Text, With<ExampleDisplay>>,
    labelled: Query<&GlobalTransform>,
    mut state: Local<ExampleState>,
    time: Res<Time>,
    input: Res<ButtonInput<KeyCode>>,
) {
    if input.pressed(KeyCode::ArrowUp) {
        state.alpha = (state.alpha + time.delta_seconds()).min(1.0);
    } else if input.pressed(KeyCode::ArrowDown) {
        state.alpha = (state.alpha - time.delta_seconds()).max(0.0);
    }

    if input.just_pressed(KeyCode::Space) {
        state.unlit = !state.unlit;
    }

    let randomize_colors = input.just_pressed(KeyCode::KeyC);

    for (material_handle, controls) in &controllable {
        let material = materials.get_mut(material_handle).unwrap();
        material.base_color.set_a(state.alpha);

        if controls.color && randomize_colors {
            material.base_color.set_r(random());
            material.base_color.set_g(random());
            material.base_color.set_b(random());
        }
        if controls.unlit {
            material.unlit = state.unlit;
        }
    }

    let (mut camera, mut camera_transform, camera_global_transform) = camera.single_mut();

    if input.just_pressed(KeyCode::KeyH) {
        camera.hdr = !camera.hdr;
    }

    let rotation = if input.pressed(KeyCode::ArrowLeft) {
        time.delta_seconds()
    } else if input.pressed(KeyCode::ArrowRight) {
        -time.delta_seconds()
    } else {
        0.0
    };

    camera_transform.rotate_around(Vec3::ZERO, Quat::from_rotation_y(rotation));

    for (mut style, label) in &mut labels {
        let world_position = labelled.get(label.entity).unwrap().translation() + Vec3::Y;

        let viewport_position = camera
            .world_to_viewport(camera_global_transform, world_position)
            .unwrap();

        style.top = Val::Px(viewport_position.y);
        style.left = Val::Px(viewport_position.x);
    }

    let mut display = display.single_mut();
    display.sections[0].value = format!(
        "  HDR: {}\nAlpha: {:.2}",
        if camera.hdr { "ON " } else { "OFF" },
        state.alpha
    );
}
examples/ui/size_constraints.rs (line 328)
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
fn update_buttons(
    mut button_query: Query<
        (Entity, &Interaction, &Constraint, &ButtonValue),
        Changed<Interaction>,
    >,
    mut bar_query: Query<&mut Style, With<Bar>>,
    mut text_query: Query<&mut Text>,
    children_query: Query<&Children>,
    mut button_activated_event: EventWriter<ButtonActivatedEvent>,
) {
    let mut style = bar_query.single_mut();
    for (button_id, interaction, constraint, value) in button_query.iter_mut() {
        match interaction {
            Interaction::Pressed => {
                button_activated_event.send(ButtonActivatedEvent(button_id));
                match constraint {
                    Constraint::FlexBasis => {
                        style.flex_basis = value.0;
                    }
                    Constraint::Width => {
                        style.width = value.0;
                    }
                    Constraint::MinWidth => {
                        style.min_width = value.0;
                    }
                    Constraint::MaxWidth => {
                        style.max_width = value.0;
                    }
                }
            }
            Interaction::Hovered => {
                if let Ok(children) = children_query.get(button_id) {
                    for &child in children {
                        if let Ok(grand_children) = children_query.get(child) {
                            for &grandchild in grand_children {
                                if let Ok(mut text) = text_query.get_mut(grandchild) {
                                    if text.sections[0].style.color != ACTIVE_TEXT_COLOR {
                                        text.sections[0].style.color = HOVERED_TEXT_COLOR;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            Interaction::None => {
                if let Ok(children) = children_query.get(button_id) {
                    for &child in children {
                        if let Ok(grand_children) = children_query.get(child) {
                            for &grandchild in grand_children {
                                if let Ok(mut text) = text_query.get_mut(grandchild) {
                                    if text.sections[0].style.color != ACTIVE_TEXT_COLOR {
                                        text.sections[0].style.color = UNHOVERED_TEXT_COLOR;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

fn update_radio_buttons_colors(
    mut event_reader: EventReader<ButtonActivatedEvent>,
    button_query: Query<(Entity, &Constraint, &Interaction)>,
    mut color_query: Query<&mut BackgroundColor>,
    mut text_query: Query<&mut Text>,
    children_query: Query<&Children>,
) {
    for &ButtonActivatedEvent(button_id) in event_reader.read() {
        let (_, target_constraint, _) = button_query.get(button_id).unwrap();
        for (id, constraint, interaction) in button_query.iter() {
            if target_constraint == constraint {
                let (border_color, inner_color, text_color) = if id == button_id {
                    (ACTIVE_BORDER_COLOR, ACTIVE_INNER_COLOR, ACTIVE_TEXT_COLOR)
                } else {
                    (
                        INACTIVE_BORDER_COLOR,
                        INACTIVE_INNER_COLOR,
                        if matches!(interaction, Interaction::Hovered) {
                            HOVERED_TEXT_COLOR
                        } else {
                            UNHOVERED_TEXT_COLOR
                        },
                    )
                };

                color_query.get_mut(id).unwrap().0 = border_color;
                if let Ok(children) = children_query.get(id) {
                    for &child in children {
                        color_query.get_mut(child).unwrap().0 = inner_color;
                        if let Ok(grand_children) = children_query.get(child) {
                            for &grandchild in grand_children {
                                if let Ok(mut text) = text_query.get_mut(grandchild) {
                                    text.sections[0].style.color = text_color;
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
source

pub fn get_many<const N: usize>( &self, entities: [Entity; N] ) -> Result<[<<D as QueryData>::ReadOnly as WorldQuery>::Item<'_>; N], QueryEntityError>

Returns the read-only query items for the given array of Entity.

The returned query items are in the same order as the input. In case of a nonexisting entity or mismatched component, a QueryEntityError is returned instead. The elements of the array do not need to be unique, unlike get_many_mut.

§See also
source

pub fn many<const N: usize>( &self, entities: [Entity; N] ) -> [<<D as QueryData>::ReadOnly as WorldQuery>::Item<'_>; N]

Returns the read-only query items for the given array of Entity.

§Panics

This method panics if there is a query mismatch or a non-existing entity.

§Examples
use bevy_ecs::prelude::*;

#[derive(Component)]
struct Targets([Entity; 3]);

#[derive(Component)]
struct Position{
    x: i8,
    y: i8
};

impl Position {
    fn distance(&self, other: &Position) -> i8 {
        // Manhattan distance is way easier to compute!
        (self.x - other.x).abs() + (self.y - other.y).abs()
    }
}

fn check_all_targets_in_range(targeting_query: Query<(Entity, &Targets, &Position)>, targets_query: Query<&Position>){
    for (targeting_entity, targets, origin) in &targeting_query {
        // We can use "destructuring" to unpack the results nicely
        let [target_1, target_2, target_3] = targets_query.many(targets.0);

        assert!(target_1.distance(origin) <= 5);
        assert!(target_2.distance(origin) <= 5);
        assert!(target_3.distance(origin) <= 5);
    }
}
§See also
  • get_many for the non-panicking version.
source

pub fn get_mut( &mut self, entity: Entity ) -> Result<<D as WorldQuery>::Item<'_>, QueryEntityError>

Returns the query item for the given Entity.

In case of a nonexisting entity or mismatched component, a QueryEntityError is returned instead.

§Example

Here, get_mut is used to retrieve the exact query item of the entity specified by the PoisonedCharacter resource.

fn poison_system(mut query: Query<&mut Health>, poisoned: Res<PoisonedCharacter>) {
    if let Ok(mut health) = query.get_mut(poisoned.character_id) {
        health.0 -= 1;
    }
}
§See also
  • get to get a read-only query item.
Examples found in repository?
examples/ecs/removal_detection.rs (line 57)
53
54
55
56
57
58
59
60
61
fn react_on_removal(mut removed: RemovedComponents<MyComponent>, mut query: Query<&mut Sprite>) {
    // `RemovedComponents<T>::read()` returns an iterator with the `Entity`s that had their
    // `Component` `T` (in this case `MyComponent`) removed at some point earlier during the frame.
    for entity in removed.read() {
        if let Ok(mut sprite) = query.get_mut(entity) {
            sprite.color.set_r(0.0);
        }
    }
}
More examples
Hide additional examples
examples/3d/update_gltf_scene.rs (line 67)
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
fn move_scene_entities(
    time: Res<Time>,
    moved_scene: Query<Entity, With<MovedScene>>,
    children: Query<&Children>,
    mut transforms: Query<&mut Transform>,
) {
    for moved_scene_entity in &moved_scene {
        let mut offset = 0.;
        for entity in children.iter_descendants(moved_scene_entity) {
            if let Ok(mut transform) = transforms.get_mut(entity) {
                transform.translation = Vec3::new(
                    offset * time.elapsed_seconds().sin() / 20.,
                    0.,
                    time.elapsed_seconds().cos() / 20.,
                );
                offset += 0.5;
            }
        }
    }
}
examples/ui/ui_texture_slice.rs (line 21)
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
fn button_system(
    mut interaction_query: Query<(&Interaction, &Children), (Changed<Interaction>, With<Button>)>,
    mut text_query: Query<&mut Text>,
) {
    for (interaction, children) in &mut interaction_query {
        let mut text = text_query.get_mut(children[0]).unwrap();
        match *interaction {
            Interaction::Pressed => {
                text.sections[0].value = "Press".to_string();
            }
            Interaction::Hovered => {
                text.sections[0].value = "Hover".to_string();
            }
            Interaction::None => {
                text.sections[0].value = "Button".to_string();
            }
        }
    }
}
examples/3d/split_screen.rs (line 240)
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
fn button_system(
    interaction_query: Query<
        (&Interaction, &TargetCamera, &RotateCamera),
        (Changed<Interaction>, With<Button>),
    >,
    mut camera_query: Query<&mut Transform, With<Camera>>,
) {
    for (interaction, target_camera, RotateCamera(direction)) in &interaction_query {
        if let Interaction::Pressed = *interaction {
            // Since TargetCamera propagates to the children, we can use it to find
            // which side of the screen the button is on.
            if let Ok(mut camera_transform) = camera_query.get_mut(target_camera.entity()) {
                let angle = match direction {
                    Direction::Left => -0.1,
                    Direction::Right => 0.1,
                };
                camera_transform.rotate_around(Vec3::ZERO, Quat::from_axis_angle(Vec3::Y, angle));
            }
        }
    }
}
examples/ui/display_and_visibility.rs (line 443)
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
fn buttons_handler<T>(
    mut left_panel_query: Query<&mut <Target<T> as TargetUpdate>::TargetComponent>,
    mut visibility_button_query: Query<(&Target<T>, &Interaction, &Children), Changed<Interaction>>,
    mut text_query: Query<&mut Text>,
) where
    T: Send + Sync,
    Target<T>: TargetUpdate + Component,
{
    for (target, interaction, children) in visibility_button_query.iter_mut() {
        if matches!(interaction, Interaction::Pressed) {
            let mut target_value = left_panel_query.get_mut(target.id).unwrap();
            for &child in children {
                if let Ok(mut text) = text_query.get_mut(child) {
                    text.sections[0].value = target.update_target(target_value.as_mut());
                    text.sections[0].style.color = if text.sections[0].value.contains("None")
                        || text.sections[0].value.contains("Hidden")
                    {
                        Color::rgb(1.0, 0.7, 0.7)
                    } else {
                        Color::WHITE
                    };
                }
            }
        }
    }
}

fn text_hover(
    mut button_query: Query<(&Interaction, &mut BackgroundColor, &Children), Changed<Interaction>>,
    mut text_query: Query<&mut Text>,
) {
    for (interaction, mut background_color, children) in button_query.iter_mut() {
        match interaction {
            Interaction::Hovered => {
                *background_color = BackgroundColor(Color::BLACK.with_a(0.6));
                for &child in children {
                    if let Ok(mut text) = text_query.get_mut(child) {
                        // Bypass change detection to avoid recomputation of the text when only changing the color
                        text.bypass_change_detection().sections[0].style.color = Color::YELLOW;
                    }
                }
            }
            _ => {
                *background_color = BackgroundColor(Color::BLACK.with_a(0.5));
                for &child in children {
                    if let Ok(mut text) = text_query.get_mut(child) {
                        text.bypass_change_detection().sections[0].style.color =
                            if text.sections[0].value.contains("None")
                                || text.sections[0].value.contains("Hidden")
                            {
                                HIDDEN_COLOR
                            } else {
                                Color::WHITE
                            };
                    }
                }
            }
        }
    }
}
examples/ui/button.rs (line 33)
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
fn button_system(
    mut interaction_query: Query<
        (
            &Interaction,
            &mut BackgroundColor,
            &mut BorderColor,
            &Children,
        ),
        (Changed<Interaction>, With<Button>),
    >,
    mut text_query: Query<&mut Text>,
) {
    for (interaction, mut color, mut border_color, children) in &mut interaction_query {
        let mut text = text_query.get_mut(children[0]).unwrap();
        match *interaction {
            Interaction::Pressed => {
                text.sections[0].value = "Press".to_string();
                *color = PRESSED_BUTTON.into();
                border_color.0 = Color::RED;
            }
            Interaction::Hovered => {
                text.sections[0].value = "Hover".to_string();
                *color = HOVERED_BUTTON.into();
                border_color.0 = Color::WHITE;
            }
            Interaction::None => {
                text.sections[0].value = "Button".to_string();
                *color = NORMAL_BUTTON.into();
                border_color.0 = Color::BLACK;
            }
        }
    }
}
source

pub fn get_many_mut<const N: usize>( &mut self, entities: [Entity; N] ) -> Result<[<D as WorldQuery>::Item<'_>; N], QueryEntityError>

Returns the query items for the given array of Entity.

The returned query items are in the same order as the input. In case of a nonexisting entity, duplicate entities or mismatched component, a QueryEntityError is returned instead.

§See also
source

pub fn many_mut<const N: usize>( &mut self, entities: [Entity; N] ) -> [<D as WorldQuery>::Item<'_>; N]

Returns the query items for the given array of Entity.

§Panics

This method panics if there is a query mismatch, a non-existing entity, or the same Entity is included more than once in the array.

§Examples
use bevy_ecs::prelude::*;

#[derive(Component)]
struct Spring{
    connected_entities: [Entity; 2],
    strength: f32,
}

#[derive(Component)]
struct Position {
    x: f32,
    y: f32,
}

#[derive(Component)]
struct Force {
    x: f32,
    y: f32,
}

fn spring_forces(spring_query: Query<&Spring>, mut mass_query: Query<(&Position, &mut Force)>){
    for spring in &spring_query {
         // We can use "destructuring" to unpack our query items nicely
         let [(position_1, mut force_1), (position_2, mut force_2)] = mass_query.many_mut(spring.connected_entities);

         force_1.x += spring.strength * (position_1.x - position_2.x);
         force_1.y += spring.strength * (position_1.y - position_2.y);

         // Silence borrow-checker: I have split your mutable borrow!
         force_2.x += spring.strength * (position_2.x - position_1.x);
         force_2.y += spring.strength * (position_2.y - position_1.y);
    }
}
§See also
  • get_many_mut for the non panicking version.
  • many to get read-only query items.
source

pub unsafe fn get_unchecked( &self, entity: Entity ) -> Result<<D as WorldQuery>::Item<'_>, QueryEntityError>

Returns the query item for the given Entity.

In case of a nonexisting entity or mismatched component, a QueryEntityError is returned instead.

§Safety

This function makes it possible to violate Rust’s aliasing guarantees. You must make sure this call does not result in multiple mutable references to the same component.

§See also
source

pub fn get_component<T>( &self, entity: Entity ) -> Result<&T, QueryComponentError>
where T: Component,

👎Deprecated since 0.13.0: Please use get and select for the exact component based on the structure of the exact query as required.

Returns a shared reference to the component T of the given Entity.

In case of a nonexisting entity or mismatched component, a QueryEntityError is returned instead.

§Example

Here, get_component is used to retrieve the Character component of the entity specified by the SelectedCharacter resource.

fn print_selected_character_name_system(
       query: Query<&Character>,
       selection: Res<SelectedCharacter>
)
{
    if let Ok(selected_character) = query.get_component::<Character>(selection.entity) {
        println!("{}", selected_character.name);
    }
}
§See also
source

pub fn get_component_mut<T>( &mut self, entity: Entity ) -> Result<Mut<'_, T>, QueryComponentError>
where T: Component,

👎Deprecated since 0.13.0: Please use get_mut and select for the exact component based on the structure of the exact query as required.

Returns a mutable reference to the component T of the given entity.

In case of a nonexisting entity, mismatched component or missing write access, a QueryComponentError is returned instead.

§Example

Here, get_component_mut is used to retrieve the Health component of the entity specified by the PoisonedCharacter resource.

fn poison_system(mut query: Query<&mut Health>, poisoned: Res<PoisonedCharacter>) {
    if let Ok(mut health) = query.get_component_mut::<Health>(poisoned.character_id) {
        health.0 -= 1;
    }
}
§See also
source

pub fn component<T>(&self, entity: Entity) -> &T
where T: Component,

👎Deprecated since 0.13.0: Please use get and select for the exact component based on the structure of the exact query as required.

Returns a shared reference to the component T of the given Entity.

§Panics

Panics in case of a nonexisting entity or mismatched component.

§See also
source

pub fn component_mut<T>(&mut self, entity: Entity) -> Mut<'_, T>
where T: Component,

👎Deprecated since 0.13.0: Please use get_mut and select for the exact component based on the structure of the exact query as required.

Returns a mutable reference to the component T of the given entity.

§Panics

Panics in case of a nonexisting entity, mismatched component or missing write access.

§See also
source

pub unsafe fn get_component_unchecked_mut<T>( &self, entity: Entity ) -> Result<Mut<'_, T>, QueryComponentError>
where T: Component,

👎Deprecated since 0.13.0: Please use get_unchecked and select for the exact component based on the structure of the exact query as required.

Returns a mutable reference to the component T of the given entity.

In case of a nonexisting entity or mismatched component, a QueryComponentError is returned instead.

§Safety

This function makes it possible to violate Rust’s aliasing guarantees. You must make sure this call does not result in multiple mutable references to the same component.

§See also
source

pub fn single(&self) -> <<D as QueryData>::ReadOnly as WorldQuery>::Item<'_>

Returns a single read-only query item when there is exactly one entity matching the query.

§Panics

This method panics if the number of query items is not exactly one.

§Example
fn player_system(query: Query<&Position, With<Player>>) {
    let player_position = query.single();
    // do something with player_position
}
§See also
Examples found in repository?
examples/ecs/iter_combinations.rs (line 159)
154
155
156
157
158
159
160
161
162
163
164
165
fn look_at_star(
    mut camera: Query<&mut Transform, (With<Camera>, Without<Star>)>,
    star: Query<&Transform, With<Star>>,
) {
    let mut camera = camera.single_mut();
    let star = star.single();
    let new_rotation = camera
        .looking_at(star.translation, Vec3::Y)
        .rotation
        .lerp(camera.rotation, 0.1);
    camera.rotation = new_rotation;
}
More examples
Hide additional examples
examples/window/screenshot.rs (line 25)
15
16
17
18
19
20
21
22
23
24
25
26
27
28
fn screenshot_on_spacebar(
    input: Res<ButtonInput<KeyCode>>,
    main_window: Query<Entity, With<PrimaryWindow>>,
    mut screenshot_manager: ResMut<ScreenshotManager>,
    mut counter: Local<u32>,
) {
    if input.just_pressed(KeyCode::Space) {
        let path = format!("./screenshot-{}.png", *counter);
        *counter += 1;
        screenshot_manager
            .save_screenshot_to_disk(main_window.single(), path)
            .unwrap();
    }
}
examples/2d/2d_viewport_to_world.rs (line 18)
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
fn draw_cursor(
    camera_query: Query<(&Camera, &GlobalTransform)>,
    windows: Query<&Window>,
    mut gizmos: Gizmos,
) {
    let (camera, camera_transform) = camera_query.single();

    let Some(cursor_position) = windows.single().cursor_position() else {
        return;
    };

    // Calculate a world position based on the cursor's position.
    let Some(point) = camera.viewport_to_world_2d(camera_transform, cursor_position) else {
        return;
    };

    gizmos.circle_2d(point, 10., Color::WHITE);
}
examples/stress_tests/bevymark.rs (line 159)
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
fn scheduled_spawner(
    mut commands: Commands,
    args: Res<Args>,
    windows: Query<&Window>,
    mut scheduled: ResMut<BirdScheduled>,
    mut counter: ResMut<BevyCounter>,
    bird_resources: ResMut<BirdResources>,
) {
    let window = windows.single();

    if scheduled.waves > 0 {
        let bird_resources = bird_resources.into_inner();
        spawn_birds(
            &mut commands,
            args.into_inner(),
            &window.resolution,
            &mut counter,
            scheduled.per_wave,
            bird_resources,
            None,
            scheduled.waves - 1,
        );

        scheduled.waves -= 1;
    }
}

#[derive(Resource)]
struct BirdResources {
    textures: Vec<Handle<Image>>,
    materials: Vec<Handle<ColorMaterial>>,
    quad: Mesh2dHandle,
    color_rng: StdRng,
    material_rng: StdRng,
    velocity_rng: StdRng,
    transform_rng: StdRng,
}

#[derive(Component)]
struct StatsText;

#[allow(clippy::too_many_arguments)]
fn setup(
    mut commands: Commands,
    args: Res<Args>,
    asset_server: Res<AssetServer>,
    mut meshes: ResMut<Assets<Mesh>>,
    material_assets: ResMut<Assets<ColorMaterial>>,
    images: ResMut<Assets<Image>>,
    windows: Query<&Window>,
    counter: ResMut<BevyCounter>,
) {
    warn!(include_str!("warning_string.txt"));

    let args = args.into_inner();
    let images = images.into_inner();

    let mut textures = Vec::with_capacity(args.material_texture_count.max(1));
    if matches!(args.mode, Mode::Sprite) || args.material_texture_count > 0 {
        textures.push(asset_server.load("branding/icon.png"));
    }
    init_textures(&mut textures, args, images);

    let material_assets = material_assets.into_inner();
    let materials = init_materials(args, &textures, material_assets);

    let mut bird_resources = BirdResources {
        textures,
        materials,
        quad: meshes
            .add(Rectangle::from_size(Vec2::splat(BIRD_TEXTURE_SIZE as f32)))
            .into(),
        color_rng: StdRng::seed_from_u64(42),
        material_rng: StdRng::seed_from_u64(42),
        velocity_rng: StdRng::seed_from_u64(42),
        transform_rng: StdRng::seed_from_u64(42),
    };

    let text_section = move |color, value: &str| {
        TextSection::new(
            value,
            TextStyle {
                font_size: 40.0,
                color,
                ..default()
            },
        )
    };

    commands.spawn(Camera2dBundle::default());
    commands
        .spawn(NodeBundle {
            style: Style {
                position_type: PositionType::Absolute,
                padding: UiRect::all(Val::Px(5.0)),
                ..default()
            },
            z_index: ZIndex::Global(i32::MAX),
            background_color: Color::BLACK.with_a(0.75).into(),
            ..default()
        })
        .with_children(|c| {
            c.spawn((
                TextBundle::from_sections([
                    text_section(Color::GREEN, "Bird Count: "),
                    text_section(Color::CYAN, ""),
                    text_section(Color::GREEN, "\nFPS (raw): "),
                    text_section(Color::CYAN, ""),
                    text_section(Color::GREEN, "\nFPS (SMA): "),
                    text_section(Color::CYAN, ""),
                    text_section(Color::GREEN, "\nFPS (EMA): "),
                    text_section(Color::CYAN, ""),
                ]),
                StatsText,
            ));
        });

    let mut scheduled = BirdScheduled {
        per_wave: args.per_wave,
        waves: args.waves,
    };

    if args.benchmark {
        let counter = counter.into_inner();
        for wave in (0..scheduled.waves).rev() {
            spawn_birds(
                &mut commands,
                args,
                &windows.single().resolution,
                counter,
                scheduled.per_wave,
                &mut bird_resources,
                Some(wave),
                wave,
            );
        }
        scheduled.waves = 0;
    }
    commands.insert_resource(bird_resources);
    commands.insert_resource(scheduled);
}

#[allow(clippy::too_many_arguments)]
fn mouse_handler(
    mut commands: Commands,
    args: Res<Args>,
    time: Res<Time>,
    mouse_button_input: Res<ButtonInput<MouseButton>>,
    windows: Query<&Window>,
    bird_resources: ResMut<BirdResources>,
    mut counter: ResMut<BevyCounter>,
    mut rng: Local<Option<StdRng>>,
    mut wave: Local<usize>,
) {
    if rng.is_none() {
        *rng = Some(StdRng::seed_from_u64(42));
    }
    let rng = rng.as_mut().unwrap();
    let window = windows.single();

    if mouse_button_input.just_released(MouseButton::Left) {
        counter.color = Color::rgb_linear(rng.gen(), rng.gen(), rng.gen());
    }

    if mouse_button_input.pressed(MouseButton::Left) {
        let spawn_count = (BIRDS_PER_SECOND as f64 * time.delta_seconds_f64()) as usize;
        spawn_birds(
            &mut commands,
            args.into_inner(),
            &window.resolution,
            &mut counter,
            spawn_count,
            bird_resources.into_inner(),
            None,
            *wave,
        );
        *wave += 1;
    }
}

fn bird_velocity_transform(
    half_extents: Vec2,
    mut translation: Vec3,
    velocity_rng: &mut StdRng,
    waves: Option<usize>,
    dt: f32,
) -> (Transform, Vec3) {
    let mut velocity = Vec3::new(MAX_VELOCITY * (velocity_rng.gen::<f32>() - 0.5), 0., 0.);

    if let Some(waves) = waves {
        // Step the movement and handle collisions as if the wave had been spawned at fixed time intervals
        // and with dt-spaced frames of simulation
        for _ in 0..(waves * (FIXED_TIMESTEP / dt).round() as usize) {
            step_movement(&mut translation, &mut velocity, dt);
            handle_collision(half_extents, &translation, &mut velocity);
        }
    }
    (
        Transform::from_translation(translation).with_scale(Vec3::splat(BIRD_SCALE)),
        velocity,
    )
}

const FIXED_DELTA_TIME: f32 = 1.0 / 60.0;

#[allow(clippy::too_many_arguments)]
fn spawn_birds(
    commands: &mut Commands,
    args: &Args,
    primary_window_resolution: &WindowResolution,
    counter: &mut BevyCounter,
    spawn_count: usize,
    bird_resources: &mut BirdResources,
    waves_to_simulate: Option<usize>,
    wave: usize,
) {
    let bird_x = (primary_window_resolution.width() / -2.) + HALF_BIRD_SIZE;
    let bird_y = (primary_window_resolution.height() / 2.) - HALF_BIRD_SIZE;

    let half_extents = 0.5
        * Vec2::new(
            primary_window_resolution.width(),
            primary_window_resolution.height(),
        );

    let color = counter.color;
    let current_count = counter.count;

    match args.mode {
        Mode::Sprite => {
            let batch = (0..spawn_count)
                .map(|count| {
                    let bird_z = if args.ordered_z {
                        (current_count + count) as f32 * 0.00001
                    } else {
                        bird_resources.transform_rng.gen::<f32>()
                    };

                    let (transform, velocity) = bird_velocity_transform(
                        half_extents,
                        Vec3::new(bird_x, bird_y, bird_z),
                        &mut bird_resources.velocity_rng,
                        waves_to_simulate,
                        FIXED_DELTA_TIME,
                    );

                    let color = if args.vary_per_instance {
                        Color::rgb_linear(
                            bird_resources.color_rng.gen(),
                            bird_resources.color_rng.gen(),
                            bird_resources.color_rng.gen(),
                        )
                    } else {
                        color
                    };
                    (
                        SpriteBundle {
                            texture: bird_resources
                                .textures
                                .choose(&mut bird_resources.material_rng)
                                .unwrap()
                                .clone(),
                            transform,
                            sprite: Sprite { color, ..default() },
                            ..default()
                        },
                        Bird { velocity },
                    )
                })
                .collect::<Vec<_>>();
            commands.spawn_batch(batch);
        }
        Mode::Mesh2d => {
            let batch = (0..spawn_count)
                .map(|count| {
                    let bird_z = if args.ordered_z {
                        (current_count + count) as f32 * 0.00001
                    } else {
                        bird_resources.transform_rng.gen::<f32>()
                    };

                    let (transform, velocity) = bird_velocity_transform(
                        half_extents,
                        Vec3::new(bird_x, bird_y, bird_z),
                        &mut bird_resources.velocity_rng,
                        waves_to_simulate,
                        FIXED_DELTA_TIME,
                    );

                    let material =
                        if args.vary_per_instance || args.material_texture_count > args.waves {
                            bird_resources
                                .materials
                                .choose(&mut bird_resources.material_rng)
                                .unwrap()
                                .clone()
                        } else {
                            bird_resources.materials[wave % bird_resources.materials.len()].clone()
                        };
                    (
                        MaterialMesh2dBundle {
                            mesh: bird_resources.quad.clone(),
                            material,
                            transform,
                            ..default()
                        },
                        Bird { velocity },
                    )
                })
                .collect::<Vec<_>>();
            commands.spawn_batch(batch);
        }
    }

    counter.count += spawn_count;
    counter.color = Color::rgb_linear(
        bird_resources.color_rng.gen(),
        bird_resources.color_rng.gen(),
        bird_resources.color_rng.gen(),
    );
}

fn step_movement(translation: &mut Vec3, velocity: &mut Vec3, dt: f32) {
    translation.x += velocity.x * dt;
    translation.y += velocity.y * dt;
    velocity.y += GRAVITY * dt;
}

fn movement_system(
    args: Res<Args>,
    time: Res<Time>,
    mut bird_query: Query<(&mut Bird, &mut Transform)>,
) {
    let dt = if args.benchmark {
        FIXED_DELTA_TIME
    } else {
        time.delta_seconds()
    };
    for (mut bird, mut transform) in &mut bird_query {
        step_movement(&mut transform.translation, &mut bird.velocity, dt);
    }
}

fn handle_collision(half_extents: Vec2, translation: &Vec3, velocity: &mut Vec3) {
    if (velocity.x > 0. && translation.x + HALF_BIRD_SIZE > half_extents.x)
        || (velocity.x <= 0. && translation.x - HALF_BIRD_SIZE < -half_extents.x)
    {
        velocity.x = -velocity.x;
    }
    let velocity_y = velocity.y;
    if velocity_y < 0. && translation.y - HALF_BIRD_SIZE < -half_extents.y {
        velocity.y = -velocity_y;
    }
    if translation.y + HALF_BIRD_SIZE > half_extents.y && velocity_y > 0.0 {
        velocity.y = 0.0;
    }
}
fn collision_system(windows: Query<&Window>, mut bird_query: Query<(&mut Bird, &Transform)>) {
    let window = windows.single();

    let half_extents = 0.5 * Vec2::new(window.width(), window.height());

    for (mut bird, transform) in &mut bird_query {
        handle_collision(half_extents, &transform.translation, &mut bird.velocity);
    }
}
examples/ui/relative_cursor_position.rs (line 76)
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
fn relative_cursor_position_system(
    relative_cursor_position_query: Query<&RelativeCursorPosition>,
    mut output_query: Query<&mut Text>,
) {
    let relative_cursor_position = relative_cursor_position_query.single();

    let mut output = output_query.single_mut();

    output.sections[0].value =
        if let Some(relative_cursor_position) = relative_cursor_position.normalized {
            format!(
                "({:.1}, {:.1})",
                relative_cursor_position.x, relative_cursor_position.y
            )
        } else {
            "unknown".to_string()
        };

    output.sections[0].style.color = if relative_cursor_position.mouse_over() {
        Color::rgb(0.1, 0.9, 0.1)
    } else {
        Color::rgb(0.9, 0.1, 0.1)
    };
}
examples/input/text_input.rs (line 186)
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
fn listen_keyboard_input_events(
    mut commands: Commands,
    mut events: EventReader<KeyboardInput>,
    mut edit_text: Query<(Entity, &mut Text), (Without<Node>, Without<Bubble>)>,
) {
    for event in events.read() {
        match event.key_code {
            KeyCode::Enter => {
                let (entity, text) = edit_text.single();
                commands.entity(entity).insert(Bubble {
                    timer: Timer::from_seconds(5.0, TimerMode::Once),
                });

                commands.spawn(Text2dBundle {
                    text: Text::from_section("".to_string(), text.sections[0].style.clone()),
                    ..default()
                });
            }
            KeyCode::Backspace => {
                edit_text.single_mut().1.sections[0].value.pop();
            }
            _ => continue,
        }
    }
}
source

pub fn get_single( &self ) -> Result<<<D as QueryData>::ReadOnly as WorldQuery>::Item<'_>, QuerySingleError>

Returns a single read-only query item when there is exactly one entity matching the query.

If the number of query items is not exactly one, a QuerySingleError is returned instead.

§Example
fn player_scoring_system(query: Query<&PlayerScore>) {
    match query.get_single() {
        Ok(PlayerScore(score)) => {
            println!("Score: {}", score);
        }
        Err(QuerySingleError::NoEntities(_)) => {
            println!("Error: There is no player!");
        }
        Err(QuerySingleError::MultipleEntities(_)) => {
            println!("Error: There is more than one player!");
        }
    }
}
§See also
Examples found in repository?
examples/audio/audio_control.rs (line 27)
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
fn update_speed(music_controller: Query<&AudioSink, With<MyMusic>>, time: Res<Time>) {
    if let Ok(sink) = music_controller.get_single() {
        sink.set_speed(((time.elapsed_seconds() / 5.0).sin() + 1.0).max(0.1));
    }
}

fn pause(
    keyboard_input: Res<ButtonInput<KeyCode>>,
    music_controller: Query<&AudioSink, With<MyMusic>>,
) {
    if keyboard_input.just_pressed(KeyCode::Space) {
        if let Ok(sink) = music_controller.get_single() {
            sink.toggle();
        }
    }
}

fn volume(
    keyboard_input: Res<ButtonInput<KeyCode>>,
    music_controller: Query<&AudioSink, With<MyMusic>>,
) {
    if let Ok(sink) = music_controller.get_single() {
        if keyboard_input.just_pressed(KeyCode::Equal) {
            sink.set_volume(sink.volume() + 0.1);
        } else if keyboard_input.just_pressed(KeyCode::Minus) {
            sink.set_volume(sink.volume() - 0.1);
        }
    }
}
More examples
Hide additional examples
examples/3d/pbr.rs (line 144)
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
fn environment_map_load_finish(
    mut commands: Commands,
    asset_server: Res<AssetServer>,
    environment_maps: Query<&EnvironmentMapLight>,
    label_query: Query<Entity, With<EnvironmentMapLabel>>,
) {
    if let Ok(environment_map) = environment_maps.get_single() {
        if asset_server.load_state(&environment_map.diffuse_map) == LoadState::Loaded
            && asset_server.load_state(&environment_map.specular_map) == LoadState::Loaded
        {
            if let Ok(label_entity) = label_query.get_single() {
                commands.entity(label_entity).despawn();
            }
        }
    }
}
examples/3d/tonemapping.rs (line 308)
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
fn drag_drop_image(
    image_mat: Query<&Handle<StandardMaterial>, With<HDRViewer>>,
    text: Query<Entity, (With<Text>, With<SceneNumber>)>,
    mut materials: ResMut<Assets<StandardMaterial>>,
    mut drop_events: EventReader<FileDragAndDrop>,
    asset_server: Res<AssetServer>,
    mut commands: Commands,
) {
    let Some(new_image) = drop_events.read().find_map(|e| match e {
        FileDragAndDrop::DroppedFile { path_buf, .. } => {
            Some(asset_server.load(path_buf.to_string_lossy().to_string()))
        }
        _ => None,
    }) else {
        return;
    };

    for mat_h in &image_mat {
        if let Some(mat) = materials.get_mut(mat_h) {
            mat.base_color_texture = Some(new_image.clone());

            // Despawn the image viewer instructions
            if let Ok(text_entity) = text.get_single() {
                commands.entity(text_entity).despawn();
            }
        }
    }
}
examples/3d/generate_custom_mesh.rs (line 93)
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
fn input_handler(
    keyboard_input: Res<ButtonInput<KeyCode>>,
    mesh_query: Query<&Handle<Mesh>, With<CustomUV>>,
    mut meshes: ResMut<Assets<Mesh>>,
    mut query: Query<&mut Transform, With<CustomUV>>,
    time: Res<Time>,
) {
    if keyboard_input.just_pressed(KeyCode::Space) {
        let mesh_handle = mesh_query.get_single().expect("Query not successful");
        let mesh = meshes.get_mut(mesh_handle).unwrap();
        toggle_texture(mesh);
    }
    if keyboard_input.pressed(KeyCode::KeyX) {
        for mut transform in &mut query {
            transform.rotate_x(time.delta_seconds() / 1.2);
        }
    }
    if keyboard_input.pressed(KeyCode::KeyY) {
        for mut transform in &mut query {
            transform.rotate_y(time.delta_seconds() / 1.2);
        }
    }
    if keyboard_input.pressed(KeyCode::KeyZ) {
        for mut transform in &mut query {
            transform.rotate_z(time.delta_seconds() / 1.2);
        }
    }
    if keyboard_input.pressed(KeyCode::KeyR) {
        for mut transform in &mut query {
            transform.look_to(Vec3::NEG_Z, Vec3::Y);
        }
    }
}
source

pub fn single_mut(&mut self) -> <D as WorldQuery>::Item<'_>

Returns a single query item when there is exactly one entity matching the query.

§Panics

This method panics if the number of query item is not exactly one.

§Example
fn regenerate_player_health_system(mut query: Query<&mut Health, With<Player>>) {
    let mut health = query.single_mut();
    health.0 += 1;
}
§See also
Examples found in repository?
examples/games/alien_cake_addict.rs (line 372)
371
372
373
374
fn scoreboard_system(game: Res<Game>, mut query: Query<&mut Text>) {
    let mut text = query.single_mut();
    text.sections[0].value = format!("Sugar Rush: {}", game.score);
}
More examples
Hide additional examples
examples/window/scale_factor_override.rs (line 70)
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
fn display_override(mut windows: Query<&mut Window>) {
    let mut window = windows.single_mut();

    window.title = format!(
        "Scale override: {:?}",
        window.resolution.scale_factor_override()
    );
}

/// This system toggles scale factor overrides when enter is pressed
fn toggle_override(input: Res<ButtonInput<KeyCode>>, mut windows: Query<&mut Window>) {
    let mut window = windows.single_mut();

    if input.just_pressed(KeyCode::Enter) {
        let scale_factor_override = window.resolution.scale_factor_override();
        window
            .resolution
            .set_scale_factor_override(scale_factor_override.xor(Some(1.0)));
    }
}

/// This system changes the scale factor override when up or down is pressed
fn change_scale_factor(input: Res<ButtonInput<KeyCode>>, mut windows: Query<&mut Window>) {
    let mut window = windows.single_mut();
    let scale_factor_override = window.resolution.scale_factor_override();
    if input.just_pressed(KeyCode::ArrowUp) {
        window
            .resolution
            .set_scale_factor_override(scale_factor_override.map(|n| n + 1.0));
    } else if input.just_pressed(KeyCode::ArrowDown) {
        window
            .resolution
            .set_scale_factor_override(scale_factor_override.map(|n| (n - 1.0).max(1.0)));
    }
}
examples/3d/3d_gizmos.rs (line 79)
78
79
80
81
82
fn rotate_camera(mut query: Query<&mut Transform, With<Camera>>, time: Res<Time>) {
    let mut transform = query.single_mut();

    transform.rotate_around(Vec3::ZERO, Quat::from_rotation_y(time.delta_seconds() / 2.));
}
tests/window/resizing.rs (line 108)
106
107
108
109
110
111
fn sync_dimensions(dim: Res<Dimensions>, mut windows: Query<&mut Window>) {
    if dim.is_changed() {
        let mut window = windows.single_mut();
        window.resolution.set(dim.width as f32, dim.height as f32);
    }
}
tests/window/minimising.rs (line 23)
21
22
23
24
25
26
27
28
fn minimise_automatically(mut windows: Query<&mut Window>, mut frames: Local<u32>) {
    if *frames == 60 {
        let mut window = windows.single_mut();
        window.set_minimized(true);
    } else {
        *frames += 1;
    }
}
examples/stress_tests/many_lights.rs (line 136)
135
136
137
138
139
140
fn move_camera(time: Res<Time>, mut camera_query: Query<&mut Transform, With<Camera>>) {
    let mut camera_transform = camera_query.single_mut();
    let delta = time.delta_seconds() * 0.15;
    camera_transform.rotate_z(delta);
    camera_transform.rotate_x(delta);
}
source

pub fn get_single_mut( &mut self ) -> Result<<D as WorldQuery>::Item<'_>, QuerySingleError>

Returns a single query item when there is exactly one entity matching the query.

If the number of query items is not exactly one, a QuerySingleError is returned instead.

§Example
fn regenerate_player_health_system(mut query: Query<&mut Health, With<Player>>) {
    let mut health = query.get_single_mut().expect("Error: Could not find a single player.");
    health.0 += 1;
}
§See also
Examples found in repository?
examples/3d/../helpers/camera_controller.rs (line 110)
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
fn run_camera_controller(
    time: Res<Time>,
    mut windows: Query<&mut Window>,
    mut mouse_events: EventReader<MouseMotion>,
    mouse_button_input: Res<ButtonInput<MouseButton>>,
    key_input: Res<ButtonInput<KeyCode>>,
    mut toggle_cursor_grab: Local<bool>,
    mut mouse_cursor_grab: Local<bool>,
    mut query: Query<(&mut Transform, &mut CameraController), With<Camera>>,
) {
    let dt = time.delta_seconds();

    if let Ok((mut transform, mut controller)) = query.get_single_mut() {
        if !controller.initialized {
            let (yaw, pitch, _roll) = transform.rotation.to_euler(EulerRot::YXZ);
            controller.yaw = yaw;
            controller.pitch = pitch;
            controller.initialized = true;
            info!("{}", *controller);
        }
        if !controller.enabled {
            mouse_events.clear();
            return;
        }

        // Handle key input
        let mut axis_input = Vec3::ZERO;
        if key_input.pressed(controller.key_forward) {
            axis_input.z += 1.0;
        }
        if key_input.pressed(controller.key_back) {
            axis_input.z -= 1.0;
        }
        if key_input.pressed(controller.key_right) {
            axis_input.x += 1.0;
        }
        if key_input.pressed(controller.key_left) {
            axis_input.x -= 1.0;
        }
        if key_input.pressed(controller.key_up) {
            axis_input.y += 1.0;
        }
        if key_input.pressed(controller.key_down) {
            axis_input.y -= 1.0;
        }

        let mut cursor_grab_change = false;
        if key_input.just_pressed(controller.keyboard_key_toggle_cursor_grab) {
            *toggle_cursor_grab = !*toggle_cursor_grab;
            cursor_grab_change = true;
        }
        if mouse_button_input.just_pressed(controller.mouse_key_cursor_grab) {
            *mouse_cursor_grab = true;
            cursor_grab_change = true;
        }
        if mouse_button_input.just_released(controller.mouse_key_cursor_grab) {
            *mouse_cursor_grab = false;
            cursor_grab_change = true;
        }
        let cursor_grab = *mouse_cursor_grab || *toggle_cursor_grab;

        // Apply movement update
        if axis_input != Vec3::ZERO {
            let max_speed = if key_input.pressed(controller.key_run) {
                controller.run_speed
            } else {
                controller.walk_speed
            };
            controller.velocity = axis_input.normalize() * max_speed;
        } else {
            let friction = controller.friction.clamp(0.0, 1.0);
            controller.velocity *= 1.0 - friction;
            if controller.velocity.length_squared() < 1e-6 {
                controller.velocity = Vec3::ZERO;
            }
        }
        let forward = *transform.forward();
        let right = *transform.right();
        transform.translation += controller.velocity.x * dt * right
            + controller.velocity.y * dt * Vec3::Y
            + controller.velocity.z * dt * forward;

        // Handle cursor grab
        if cursor_grab_change {
            if cursor_grab {
                for mut window in &mut windows {
                    if !window.focused {
                        continue;
                    }

                    window.cursor.grab_mode = CursorGrabMode::Locked;
                    window.cursor.visible = false;
                }
            } else {
                for mut window in &mut windows {
                    window.cursor.grab_mode = CursorGrabMode::None;
                    window.cursor.visible = true;
                }
            }
        }

        // Handle mouse input
        let mut mouse_delta = Vec2::ZERO;
        if cursor_grab {
            for mouse_event in mouse_events.read() {
                mouse_delta += mouse_event.delta;
            }
        } else {
            mouse_events.clear();
        }

        if mouse_delta != Vec2::ZERO {
            // Apply look update
            controller.pitch = (controller.pitch
                - mouse_delta.y * RADIANS_PER_DOT * controller.sensitivity)
                .clamp(-PI / 2., PI / 2.);
            controller.yaw -= mouse_delta.x * RADIANS_PER_DOT * controller.sensitivity;
            transform.rotation =
                Quat::from_euler(EulerRot::ZYX, 0.0, controller.yaw, controller.pitch);
        }
    }
}
source

pub fn is_empty(&self) -> bool

Returns true if there are no query items.

§Example

Here, the score is increased only if an entity with a Player component is present in the world:

fn update_score_system(query: Query<(), With<Player>>, mut score: ResMut<Score>) {
    if !query.is_empty() {
        score.0 += 1;
    }
}
Examples found in repository?
examples/games/stepping.rs (line 238)
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
fn update_ui(
    mut commands: Commands,
    state: Res<State>,
    stepping: Res<Stepping>,
    mut ui: Query<(Entity, &mut Text, &Visibility), With<SteppingUi>>,
) {
    if ui.is_empty() {
        return;
    }

    // ensure the UI is only visible when stepping is enabled
    let (ui, mut text, vis) = ui.single_mut();
    match (vis, stepping.is_enabled()) {
        (Visibility::Hidden, true) => {
            commands.entity(ui).insert(Visibility::Inherited);
        }
        (Visibility::Hidden, false) | (_, true) => (),
        (_, false) => {
            commands.entity(ui).insert(Visibility::Hidden);
        }
    }

    // if we're not stepping, there's nothing more to be done here.
    if !stepping.is_enabled() {
        return;
    }

    let (cursor_schedule, cursor_system) = match stepping.cursor() {
        // no cursor means stepping isn't enabled, so we're done here
        None => return,
        Some(c) => c,
    };

    for (schedule, system, text_index) in &state.systems {
        let mark = if &cursor_schedule == schedule && *system == cursor_system {
            "-> "
        } else {
            "   "
        };
        text.sections[*text_index].value = mark.to_string();
    }
}
More examples
Hide additional examples
examples/3d/irradiance_volumes.rs (line 567)
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
fn create_cubes(
    image_assets: Res<Assets<Image>>,
    mut commands: Commands,
    irradiance_volumes: Query<(&IrradianceVolume, &GlobalTransform)>,
    voxel_cube_parents: Query<Entity, With<VoxelCubeParent>>,
    voxel_cubes: Query<Entity, With<VoxelCube>>,
    example_assets: Res<ExampleAssets>,
    mut voxel_visualization_material_assets: ResMut<Assets<VoxelVisualizationMaterial>>,
) {
    // If voxel cubes have already been spawned, don't do anything.
    if !voxel_cubes.is_empty() {
        return;
    }

    let Some(voxel_cube_parent) = voxel_cube_parents.iter().next() else {
        return;
    };

    for (irradiance_volume, global_transform) in irradiance_volumes.iter() {
        let Some(image) = image_assets.get(&irradiance_volume.voxels) else {
            continue;
        };

        let resolution = image.texture_descriptor.size;

        let voxel_cube_material = voxel_visualization_material_assets.add(ExtendedMaterial {
            base: StandardMaterial::from(Color::RED),
            extension: VoxelVisualizationExtension {
                irradiance_volume_info: VoxelVisualizationIrradianceVolumeInfo {
                    transform: VOXEL_TRANSFORM.inverse(),
                    inverse_transform: VOXEL_TRANSFORM,
                    resolution: uvec3(
                        resolution.width,
                        resolution.height,
                        resolution.depth_or_array_layers,
                    ),
                    intensity: IRRADIANCE_VOLUME_INTENSITY,
                },
            },
        });

        let scale = vec3(
            1.0 / resolution.width as f32,
            1.0 / resolution.height as f32,
            1.0 / resolution.depth_or_array_layers as f32,
        );

        // Spawn a cube for each voxel.
        for z in 0..resolution.depth_or_array_layers {
            for y in 0..resolution.height {
                for x in 0..resolution.width {
                    let uvw = (uvec3(x, y, z).as_vec3() + 0.5) * scale - 0.5;
                    let pos = global_transform.transform_point(uvw);
                    let voxel_cube = commands
                        .spawn(MaterialMeshBundle {
                            mesh: example_assets.voxel_cube.clone(),
                            material: voxel_cube_material.clone(),
                            transform: Transform::from_scale(Vec3::splat(VOXEL_CUBE_SCALE))
                                .with_translation(pos),
                            ..default()
                        })
                        .insert(VoxelCube)
                        .insert(NotShadowCaster)
                        .id();

                    commands.entity(voxel_cube_parent).add_child(voxel_cube);
                }
            }
        }
    }
}
source

pub fn contains(&self, entity: Entity) -> bool

Returns true if the given Entity matches the query.

§Example
fn targeting_system(in_range_query: Query<&InRange>, target: Res<Target>) {
    if in_range_query.contains(target.entity) {
        println!("Bam!")
    }
}
source

pub fn transmute_lens<NewD>(&mut self) -> QueryLens<'_, NewD>
where NewD: QueryData,

Returns a QueryLens that can be used to get a query with a more general fetch.

For example, this can transform a Query<(&A, &mut B)> to a Query<&B>. This can be useful for passing the query to another function. Note that since filter terms are dropped, non-archetypal filters like Added and Changed will not be respected. To maintain or change filter terms see Self::transmute_lens_filtered

§Panics

This will panic if NewD is not a subset of the original fetch Q

§Example
fn reusable_function(lens: &mut QueryLens<&A>) {
    assert_eq!(lens.query().single().0, 10);
}

// We can use the function in a system that takes the exact query.
fn system_1(mut query: Query<&A>) {
    reusable_function(&mut query.as_query_lens());
}

// We can also use it with a query that does not match exactly
// by transmuting it.
fn system_2(mut query: Query<(&mut A, &B)>) {
    let mut lens = query.transmute_lens::<&A>();
    reusable_function(&mut lens);
}
§Allowed Transmutes

Besides removing parameters from the query, you can also make limited changes to the types of paramters.

  • Can always add/remove Entity
  • Ref<T> <-> &T
  • &mut T -> &T
  • &mut T -> Ref<T>
  • EntityMut -> EntityRef
source

pub fn transmute_lens_filtered<NewD, NewF>( &mut self ) -> QueryLens<'_, NewD, NewF>
where NewD: QueryData, NewF: QueryFilter,

Equivalent to Self::transmute_lens but also includes a QueryFilter type.

Note that the lens will iterate the same tables and archetypes as the original query. This means that additional archetypal query terms like With and Without will not necessarily be respected and non-archetypal terms like Added and Changed will only be respected if they are in the type signature.

source

pub fn as_query_lens(&mut self) -> QueryLens<'_, D>

Gets a QueryLens with the same accesses as the existing query

source§

impl<'w, 's, D, F> Query<'w, 's, D, F>

source

pub fn get_inner( &self, entity: Entity ) -> Result<<<D as QueryData>::ReadOnly as WorldQuery>::Item<'w>, QueryEntityError>

Returns the query item for the given Entity, with the actual “inner” world lifetime.

In case of a nonexisting entity or mismatched component, a QueryEntityError is returned instead.

This can only return immutable data (mutable data will be cast to an immutable form). See get_mut for queries that contain at least one mutable component.

§Example

Here, get is used to retrieve the exact query item of the entity specified by the SelectedCharacter resource.

fn print_selected_character_name_system(
       query: Query<&Character>,
       selection: Res<SelectedCharacter>
)
{
    if let Ok(selected_character) = query.get(selection.entity) {
        println!("{}", selected_character.name);
    }
}
source

pub fn iter_inner(&self) -> QueryIter<'w, 's, <D as QueryData>::ReadOnly, F>

Returns an Iterator over the query items, with the actual “inner” world lifetime.

This can only return immutable data (mutable data will be cast to an immutable form). See Self::iter_mut for queries that contain at least one mutable component.

§Example

Here, the report_names_system iterates over the Player component of every entity that contains it:

fn report_names_system(query: Query<&Player>) {
    for player in &query {
        println!("Say hello to {}!", player.name);
    }
}

Trait Implementations§

source§

impl<D, F> Debug for Query<'_, '_, D, F>
where D: QueryData, F: QueryFilter,

source§

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

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

impl<'w, 'q, Q, F> From<&'q mut Query<'w, '_, Q, F>> for QueryLens<'q, Q, F>
where Q: QueryData, F: QueryFilter,

source§

fn from(value: &'q mut Query<'w, '_, Q, F>) -> QueryLens<'q, Q, F>

Converts to this type from the input type.
source§

impl<'w, 's, Q, F> From<&'s mut QueryLens<'w, Q, F>> for Query<'w, 's, Q, F>
where Q: QueryData, F: QueryFilter,

source§

fn from(value: &'s mut QueryLens<'w, Q, F>) -> Query<'w, 's, Q, F>

Converts to this type from the input type.
source§

impl<'w, 's, D, F> HierarchyQueryExt<'w, 's, D, F> for Query<'w, 's, D, F>
where D: QueryData, F: QueryFilter,

source§

fn iter_descendants(&'w self, entity: Entity) -> DescendantIter<'w, 's, D, F>
where <D as QueryData>::ReadOnly: WorldQuery<Item<'w> = &'w Children>,

Returns an Iterator of Entitys over all of entitys descendants. Read more
source§

fn iter_ancestors(&'w self, entity: Entity) -> AncestorIter<'w, 's, D, F>
where <D as QueryData>::ReadOnly: WorldQuery<Item<'w> = &'w Parent>,

Returns an Iterator of Entitys over all of entitys ancestors. Read more
source§

impl<'w, 's, D, F> IntoIterator for &'w Query<'_, 's, D, F>
where D: QueryData, F: QueryFilter,

§

type Item = <<D as QueryData>::ReadOnly as WorldQuery>::Item<'w>

The type of the elements being iterated over.
§

type IntoIter = QueryIter<'w, 's, <D as QueryData>::ReadOnly, F>

Which kind of iterator are we turning this into?
source§

fn into_iter(self) -> <&'w Query<'_, 's, D, F> as IntoIterator>::IntoIter

Creates an iterator from a value. Read more
source§

impl<'w, 's, D, F> IntoIterator for &'w mut Query<'_, 's, D, F>
where D: QueryData, F: QueryFilter,

§

type Item = <D as WorldQuery>::Item<'w>

The type of the elements being iterated over.
§

type IntoIter = QueryIter<'w, 's, D, F>

Which kind of iterator are we turning this into?
source§

fn into_iter(self) -> <&'w mut Query<'_, 's, D, F> as IntoIterator>::IntoIter

Creates an iterator from a value. Read more
source§

impl<D, F> SystemParam for Query<'_, '_, D, F>
where D: QueryData + 'static, F: QueryFilter + 'static,

§

type State = QueryState<D, F>

Used to store data which persists across invocations of a system.
§

type Item<'w, 's> = Query<'w, 's, D, F>

The item type returned when constructing this system param. The value of this associated type should be Self, instantiated with new lifetimes. Read more
source§

fn init_state( world: &mut World, system_meta: &mut SystemMeta ) -> <Query<'_, '_, D, F> as SystemParam>::State

Registers any World access used by this SystemParam and creates a new instance of this param’s State.
source§

fn new_archetype( state: &mut <Query<'_, '_, D, F> as SystemParam>::State, archetype: &Archetype, system_meta: &mut SystemMeta )

For the specified Archetype, registers the components accessed by this SystemParam (if applicable).
source§

unsafe fn get_param<'w, 's>( state: &'s mut <Query<'_, '_, D, F> as SystemParam>::State, system_meta: &SystemMeta, world: UnsafeWorldCell<'w>, change_tick: Tick ) -> <Query<'_, '_, D, F> as SystemParam>::Item<'w, 's>

Creates a parameter to be passed into a SystemParamFunction. Read more
source§

fn apply(state: &mut Self::State, system_meta: &SystemMeta, world: &mut World)

Applies any deferred mutations stored in this SystemParam’s state. This is used to apply Commands during apply_deferred.
source§

impl<'w, 's, D, F> ReadOnlySystemParam for Query<'w, 's, D, F>
where D: ReadOnlyQueryData + 'static, F: QueryFilter + 'static,

Auto Trait Implementations§

§

impl<'world, 'state, D, F> Freeze for Query<'world, 'state, D, F>
where F: WorldQuery, D: WorldQuery,

§

impl<'world, 'state, D, F = ()> !RefUnwindSafe for Query<'world, 'state, D, F>

§

impl<'world, 'state, D, F> Send for Query<'world, 'state, D, F>
where F: WorldQuery, D: WorldQuery,

§

impl<'world, 'state, D, F> Sync for Query<'world, 'state, D, F>
where F: WorldQuery, D: WorldQuery,

§

impl<'world, 'state, D, F> Unpin for Query<'world, 'state, D, F>
where F: WorldQuery, D: WorldQuery,

§

impl<'world, 'state, D, F = ()> !UnwindSafe for Query<'world, 'state, D, F>

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<Image>) -> 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> 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> DowncastSync for T
where T: Any + Send + Sync,

source§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Send + Sync>

Convert Arc<Trait> (where Trait: Downcast) to Arc<Any>. Arc<Any> can then be further downcast into Arc<ConcreteType> where ConcreteType implements Trait.
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> 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, U> ToSample<U> for T
where U: FromSample<T>,

source§

fn to_sample_(self) -> U

source§

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

§

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>,

§

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<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>,

source§

impl<T> Settings for T
where T: 'static + Send + Sync,

source§

impl<T> WasmNotSend for T
where T: Send,

source§

impl<T> WasmNotSendSync for T

source§

impl<T> WasmNotSync for T
where T: Sync,