Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/crates/bevy_ecs/src/system/query.rs
6604 views
1
use bevy_utils::prelude::DebugName;
2
3
use crate::{
4
batching::BatchingStrategy,
5
component::Tick,
6
entity::{Entity, EntityDoesNotExistError, EntityEquivalent, EntitySet, UniqueEntityArray},
7
query::{
8
DebugCheckedUnwrap, NopWorldQuery, QueryCombinationIter, QueryData, QueryEntityError,
9
QueryFilter, QueryIter, QueryManyIter, QueryManyUniqueIter, QueryParIter, QueryParManyIter,
10
QueryParManyUniqueIter, QuerySingleError, QueryState, ROQueryItem, ReadOnlyQueryData,
11
},
12
world::unsafe_world_cell::UnsafeWorldCell,
13
};
14
use core::{
15
marker::PhantomData,
16
mem::MaybeUninit,
17
ops::{Deref, DerefMut},
18
};
19
20
/// A [system parameter] that provides selective access to the [`Component`] data stored in a [`World`].
21
///
22
/// Queries enable systems to access [entity identifiers] and [components] without requiring direct access to the [`World`].
23
/// Its iterators and getter methods return *query items*, which are types containing data related to an entity.
24
///
25
/// `Query` is a generic data structure that accepts two type parameters:
26
///
27
/// - **`D` (query data)**:
28
/// The type of data fetched by the query, which will be returned as the query item.
29
/// Only entities that match the requested data will generate an item.
30
/// Must implement the [`QueryData`] trait.
31
/// - **`F` (query filter)**:
32
/// An optional set of conditions that determine whether query items should be kept or discarded.
33
/// This defaults to [`unit`], which means no additional filters will be applied.
34
/// Must implement the [`QueryFilter`] trait.
35
///
36
/// [system parameter]: crate::system::SystemParam
37
/// [`Component`]: crate::component::Component
38
/// [`World`]: crate::world::World
39
/// [entity identifiers]: Entity
40
/// [components]: crate::component::Component
41
///
42
/// # Similar parameters
43
///
44
/// `Query` has few sibling [`SystemParam`]s, which perform additional validation:
45
///
46
/// - [`Single`] - Exactly one matching query item.
47
/// - [`Option<Single>`] - Zero or one matching query item.
48
/// - [`Populated`] - At least one matching query item.
49
///
50
/// These parameters will prevent systems from running if their requirements are not met.
51
///
52
/// [`SystemParam`]: crate::system::system_param::SystemParam
53
/// [`Option<Single>`]: Single
54
///
55
/// # System parameter declaration
56
///
57
/// A query should always be declared as a system parameter.
58
/// This section shows the most common idioms involving the declaration of `Query`.
59
///
60
/// ## Component access
61
///
62
/// You can fetch an entity's component by specifying a reference to that component in the query's data parameter:
63
///
64
/// ```
65
/// # use bevy_ecs::prelude::*;
66
/// #
67
/// # #[derive(Component)]
68
/// # struct ComponentA;
69
/// #
70
/// // A component can be accessed by a shared reference...
71
/// fn immutable_query(query: Query<&ComponentA>) {
72
/// // ...
73
/// }
74
///
75
/// // ...or by a mutable reference.
76
/// fn mutable_query(query: Query<&mut ComponentA>) {
77
/// // ...
78
/// }
79
/// #
80
/// # bevy_ecs::system::assert_is_system(immutable_query);
81
/// # bevy_ecs::system::assert_is_system(mutable_query);
82
/// ```
83
///
84
/// Note that components need to be behind a reference (`&` or `&mut`), or the query will not compile:
85
///
86
/// ```compile_fail,E0277
87
/// # use bevy_ecs::prelude::*;
88
/// #
89
/// # #[derive(Component)]
90
/// # struct ComponentA;
91
/// #
92
/// // This needs to be `&ComponentA` or `&mut ComponentA` in order to compile.
93
/// fn invalid_query(query: Query<ComponentA>) {
94
/// // ...
95
/// }
96
/// ```
97
///
98
/// ## Query filtering
99
///
100
/// Setting the query filter type parameter will ensure that each query item satisfies the given condition:
101
///
102
/// ```
103
/// # use bevy_ecs::prelude::*;
104
/// #
105
/// # #[derive(Component)]
106
/// # struct ComponentA;
107
/// #
108
/// # #[derive(Component)]
109
/// # struct ComponentB;
110
/// #
111
/// // `ComponentA` data will be accessed, but only for entities that also contain `ComponentB`.
112
/// fn filtered_query(query: Query<&ComponentA, With<ComponentB>>) {
113
/// // ...
114
/// }
115
/// #
116
/// # bevy_ecs::system::assert_is_system(filtered_query);
117
/// ```
118
///
119
/// Note that the filter is `With<ComponentB>`, not `With<&ComponentB>`. Unlike query data, `With`
120
/// does not require components to be behind a reference.
121
///
122
/// ## `QueryData` or `QueryFilter` tuples
123
///
124
/// Using [`tuple`]s, each `Query` type parameter can contain multiple elements.
125
///
126
/// In the following example two components are accessed simultaneously, and the query items are
127
/// filtered on two conditions:
128
///
129
/// ```
130
/// # use bevy_ecs::prelude::*;
131
/// #
132
/// # #[derive(Component)]
133
/// # struct ComponentA;
134
/// #
135
/// # #[derive(Component)]
136
/// # struct ComponentB;
137
/// #
138
/// # #[derive(Component)]
139
/// # struct ComponentC;
140
/// #
141
/// # #[derive(Component)]
142
/// # struct ComponentD;
143
/// #
144
/// fn complex_query(
145
/// query: Query<(&mut ComponentA, &ComponentB), (With<ComponentC>, Without<ComponentD>)>
146
/// ) {
147
/// // ...
148
/// }
149
/// #
150
/// # bevy_ecs::system::assert_is_system(complex_query);
151
/// ```
152
///
153
/// Note that this currently only works on tuples with 15 or fewer items. You may nest tuples to
154
/// get around this limit:
155
///
156
/// ```
157
/// # use bevy_ecs::prelude::*;
158
/// #
159
/// # #[derive(Component)]
160
/// # struct ComponentA;
161
/// #
162
/// # #[derive(Component)]
163
/// # struct ComponentB;
164
/// #
165
/// # #[derive(Component)]
166
/// # struct ComponentC;
167
/// #
168
/// # #[derive(Component)]
169
/// # struct ComponentD;
170
/// #
171
/// fn nested_query(
172
/// query: Query<(&ComponentA, &ComponentB, (&mut ComponentC, &mut ComponentD))>
173
/// ) {
174
/// // ...
175
/// }
176
/// #
177
/// # bevy_ecs::system::assert_is_system(nested_query);
178
/// ```
179
///
180
/// ## Entity identifier access
181
///
182
/// You can access [`Entity`], the entity identifier, by including it in the query data parameter:
183
///
184
/// ```
185
/// # use bevy_ecs::prelude::*;
186
/// #
187
/// # #[derive(Component)]
188
/// # struct ComponentA;
189
/// #
190
/// fn entity_id_query(query: Query<(Entity, &ComponentA)>) {
191
/// // ...
192
/// }
193
/// #
194
/// # bevy_ecs::system::assert_is_system(entity_id_query);
195
/// ```
196
///
197
/// Be aware that [`Entity`] is not a component, so it does not need to be behind a reference.
198
///
199
/// ## Optional component access
200
///
201
/// A component can be made optional by wrapping it into an [`Option`]. In the following example, a
202
/// query item will still be generated even if the queried entity does not contain `ComponentB`.
203
/// When this is the case, `Option<&ComponentB>`'s corresponding value will be `None`.
204
///
205
/// ```
206
/// # use bevy_ecs::prelude::*;
207
/// #
208
/// # #[derive(Component)]
209
/// # struct ComponentA;
210
/// #
211
/// # #[derive(Component)]
212
/// # struct ComponentB;
213
/// #
214
/// // Queried items must contain `ComponentA`. If they also contain `ComponentB`, its value will
215
/// // be fetched as well.
216
/// fn optional_component_query(query: Query<(&ComponentA, Option<&ComponentB>)>) {
217
/// // ...
218
/// }
219
/// #
220
/// # bevy_ecs::system::assert_is_system(optional_component_query);
221
/// ```
222
///
223
/// Optional components can hurt performance in some cases, so please read the [performance]
224
/// section to learn more about them. Additionally, if you need to declare several optional
225
/// components, you may be interested in using [`AnyOf`].
226
///
227
/// [performance]: #performance
228
/// [`AnyOf`]: crate::query::AnyOf
229
///
230
/// ## Disjoint queries
231
///
232
/// A system cannot contain two queries that break Rust's mutability rules, or else it will panic
233
/// when initialized. This can often be fixed with the [`Without`] filter, which makes the queries
234
/// disjoint.
235
///
236
/// In the following example, the two queries can mutably access the same `&mut Health` component
237
/// if an entity has both the `Player` and `Enemy` components. Bevy will catch this and panic,
238
/// however, instead of breaking Rust's mutability rules:
239
///
240
/// ```should_panic
241
/// # use bevy_ecs::prelude::*;
242
/// #
243
/// # #[derive(Component)]
244
/// # struct Health;
245
/// #
246
/// # #[derive(Component)]
247
/// # struct Player;
248
/// #
249
/// # #[derive(Component)]
250
/// # struct Enemy;
251
/// #
252
/// fn randomize_health(
253
/// player_query: Query<&mut Health, With<Player>>,
254
/// enemy_query: Query<&mut Health, With<Enemy>>,
255
/// ) {
256
/// // ...
257
/// }
258
/// #
259
/// # bevy_ecs::system::assert_system_does_not_conflict(randomize_health);
260
/// ```
261
///
262
/// Adding a [`Without`] filter will disjoint the queries. In the following example, any entity
263
/// that has both the `Player` and `Enemy` components will be excluded from _both_ queries:
264
///
265
/// ```
266
/// # use bevy_ecs::prelude::*;
267
/// #
268
/// # #[derive(Component)]
269
/// # struct Health;
270
/// #
271
/// # #[derive(Component)]
272
/// # struct Player;
273
/// #
274
/// # #[derive(Component)]
275
/// # struct Enemy;
276
/// #
277
/// fn randomize_health(
278
/// player_query: Query<&mut Health, (With<Player>, Without<Enemy>)>,
279
/// enemy_query: Query<&mut Health, (With<Enemy>, Without<Player>)>,
280
/// ) {
281
/// // ...
282
/// }
283
/// #
284
/// # bevy_ecs::system::assert_system_does_not_conflict(randomize_health);
285
/// ```
286
///
287
/// An alternative solution to this problem would be to wrap the conflicting queries in
288
/// [`ParamSet`].
289
///
290
/// [`Without`]: crate::query::Without
291
/// [`ParamSet`]: crate::system::ParamSet
292
///
293
/// ## Whole Entity Access
294
///
295
/// [`EntityRef`] can be used in a query to gain read-only access to all components of an entity.
296
/// This is useful when dynamically fetching components instead of baking them into the query type.
297
///
298
/// ```
299
/// # use bevy_ecs::prelude::*;
300
/// #
301
/// # #[derive(Component)]
302
/// # struct ComponentA;
303
/// #
304
/// fn all_components_query(query: Query<(EntityRef, &ComponentA)>) {
305
/// // ...
306
/// }
307
/// #
308
/// # bevy_ecs::system::assert_is_system(all_components_query);
309
/// ```
310
///
311
/// As [`EntityRef`] can read any component on an entity, a query using it will conflict with *any*
312
/// mutable component access.
313
///
314
/// ```should_panic
315
/// # use bevy_ecs::prelude::*;
316
/// #
317
/// # #[derive(Component)]
318
/// # struct ComponentA;
319
/// #
320
/// // `EntityRef` provides read access to *all* components on an entity. When combined with
321
/// // `&mut ComponentA` in the same query, it creates a conflict because `EntityRef` could read
322
/// // `&ComponentA` while `&mut ComponentA` attempts to modify it - violating Rust's borrowing
323
/// // rules.
324
/// fn invalid_query(query: Query<(EntityRef, &mut ComponentA)>) {
325
/// // ...
326
/// }
327
/// #
328
/// # bevy_ecs::system::assert_system_does_not_conflict(invalid_query);
329
/// ```
330
///
331
/// It is strongly advised to couple [`EntityRef`] queries with the use of either [`With`] /
332
/// [`Without`] filters or [`ParamSet`]s. Not only does this improve the performance and
333
/// parallelization of the system, but it enables systems to gain mutable access to other
334
/// components:
335
///
336
/// ```
337
/// # use bevy_ecs::prelude::*;
338
/// #
339
/// # #[derive(Component)]
340
/// # struct ComponentA;
341
/// #
342
/// # #[derive(Component)]
343
/// # struct ComponentB;
344
/// #
345
/// // The first query only reads entities that have `ComponentA`, while the second query only
346
/// // modifies entities that *don't* have `ComponentA`. Because neither query will access the same
347
/// // entity, this system does not conflict.
348
/// fn disjoint_query(
349
/// query_a: Query<EntityRef, With<ComponentA>>,
350
/// query_b: Query<&mut ComponentB, Without<ComponentA>>,
351
/// ) {
352
/// // ...
353
/// }
354
/// #
355
/// # bevy_ecs::system::assert_system_does_not_conflict(disjoint_query);
356
/// ```
357
///
358
/// The fundamental rule: [`EntityRef`]'s ability to read all components means it can never
359
/// coexist with mutable access. [`With`] / [`Without`] filters can guarantee this by keeping the
360
/// queries on completely separate entities.
361
///
362
/// [`EntityRef`]: crate::world::EntityRef
363
/// [`With`]: crate::query::With
364
///
365
/// # Accessing query items
366
///
367
/// The following table summarizes the behavior of safe methods that can be used to get query
368
/// items:
369
///
370
/// |Query methods|Effect|
371
/// |-|-|
372
/// |[`iter`]\[[`_mut`][`iter_mut`]\]|Returns an iterator over all query items.|
373
/// |[`iter[_mut]().for_each()`][`for_each`],<br />[`par_iter`]\[[`_mut`][`par_iter_mut`]\]|Runs a specified function for each query item.|
374
/// |[`iter_many`]\[[`_unique`][`iter_many_unique`]\]\[[`_mut`][`iter_many_mut`]\]|Iterates over query items that match a list of entities.|
375
/// |[`iter_combinations`]\[[`_mut`][`iter_combinations_mut`]\]|Iterates over all combinations of query items.|
376
/// |[`single`](Self::single)\[[`_mut`][`single_mut`]\]|Returns a single query item if only one exists.|
377
/// |[`get`]\[[`_mut`][`get_mut`]\]|Returns the query item for a specified entity.|
378
/// |[`get_many`]\[[`_unique`][`get_many_unique`]\]\[[`_mut`][`get_many_mut`]\]|Returns all query items that match a list of entities.|
379
///
380
/// There are two methods for each type of query operation: immutable and mutable (ending with `_mut`).
381
/// When using immutable methods, the query items returned are of type [`ROQueryItem`], a read-only version of the query item.
382
/// In this circumstance, every mutable reference in the query fetch type parameter is substituted by a shared reference.
383
///
384
/// [`iter`]: Self::iter
385
/// [`iter_mut`]: Self::iter_mut
386
/// [`for_each`]: #iteratorfor_each
387
/// [`par_iter`]: Self::par_iter
388
/// [`par_iter_mut`]: Self::par_iter_mut
389
/// [`iter_many`]: Self::iter_many
390
/// [`iter_many_unique`]: Self::iter_many_unique
391
/// [`iter_many_mut`]: Self::iter_many_mut
392
/// [`iter_combinations`]: Self::iter_combinations
393
/// [`iter_combinations_mut`]: Self::iter_combinations_mut
394
/// [`single_mut`]: Self::single_mut
395
/// [`get`]: Self::get
396
/// [`get_mut`]: Self::get_mut
397
/// [`get_many`]: Self::get_many
398
/// [`get_many_unique`]: Self::get_many_unique
399
/// [`get_many_mut`]: Self::get_many_mut
400
///
401
/// # Performance
402
///
403
/// Creating a `Query` is a low-cost constant operation. Iterating it, on the other hand, fetches
404
/// data from the world and generates items, which can have a significant computational cost.
405
///
406
/// Two systems cannot be executed in parallel if both access the same component type where at
407
/// least one of the accesses is mutable. Because of this, it is recommended for queries to only
408
/// fetch mutable access to components when necessary, since immutable access can be parallelized.
409
///
410
/// Query filters ([`With`] / [`Without`]) can improve performance because they narrow the kinds of
411
/// entities that can be fetched. Systems that access fewer kinds of entities are more likely to be
412
/// parallelized by the scheduler.
413
///
414
/// On the other hand, be careful using optional components (`Option<&ComponentA>`) and
415
/// [`EntityRef`] because they broaden the amount of entities kinds that can be accessed. This is
416
/// especially true of a query that _only_ fetches optional components or [`EntityRef`], as the
417
/// query would iterate over all entities in the world.
418
///
419
/// There are two types of [component storage types]: [`Table`] and [`SparseSet`]. [`Table`] offers
420
/// fast iteration speeds, but slower insertion and removal speeds. [`SparseSet`] is the opposite:
421
/// it offers fast component insertion and removal speeds, but slower iteration speeds.
422
///
423
/// The following table compares the computational complexity of the various methods and
424
/// operations, where:
425
///
426
/// - **n** is the number of entities that match the query.
427
/// - **r** is the number of elements in a combination.
428
/// - **k** is the number of involved entities in the operation.
429
/// - **a** is the number of archetypes in the world.
430
/// - **C** is the [binomial coefficient], used to count combinations. <sub>n</sub>C<sub>r</sub> is
431
/// read as "*n* choose *r*" and is equivalent to the number of distinct unordered subsets of *r*
432
/// elements that can be taken from a set of *n* elements.
433
///
434
/// |Query operation|Computational complexity|
435
/// |-|-|
436
/// |[`iter`]\[[`_mut`][`iter_mut`]\]|O(n)|
437
/// |[`iter[_mut]().for_each()`][`for_each`],<br/>[`par_iter`]\[[`_mut`][`par_iter_mut`]\]|O(n)|
438
/// |[`iter_many`]\[[`_mut`][`iter_many_mut`]\]|O(k)|
439
/// |[`iter_combinations`]\[[`_mut`][`iter_combinations_mut`]\]|O(<sub>n</sub>C<sub>r</sub>)|
440
/// |[`single`](Self::single)\[[`_mut`][`single_mut`]\]|O(a)|
441
/// |[`get`]\[[`_mut`][`get_mut`]\]|O(1)|
442
/// |[`get_many`]|O(k)|
443
/// |[`get_many_mut`]|O(k<sup>2</sup>)|
444
/// |Archetype-based filtering ([`With`], [`Without`], [`Or`])|O(a)|
445
/// |Change detection filtering ([`Added`], [`Changed`], [`Spawned`])|O(a + n)|
446
///
447
/// [component storage types]: crate::component::StorageType
448
/// [`Table`]: crate::storage::Table
449
/// [`SparseSet`]: crate::storage::SparseSet
450
/// [binomial coefficient]: https://en.wikipedia.org/wiki/Binomial_coefficient
451
/// [`Or`]: crate::query::Or
452
/// [`Added`]: crate::query::Added
453
/// [`Changed`]: crate::query::Changed
454
/// [`Spawned`]: crate::query::Spawned
455
///
456
/// # `Iterator::for_each`
457
///
458
/// The `for_each` methods appear to be generally faster than `for`-loops when run on worlds with
459
/// high archetype fragmentation, and may enable additional optimizations like [autovectorization]. It
460
/// is strongly advised to only use [`Iterator::for_each`] if it tangibly improves performance.
461
/// *Always* profile or benchmark before and after the change!
462
///
463
/// ```rust
464
/// # use bevy_ecs::prelude::*;
465
/// #
466
/// # #[derive(Component)]
467
/// # struct ComponentA;
468
/// #
469
/// fn system(query: Query<&ComponentA>) {
470
/// // This may result in better performance...
471
/// query.iter().for_each(|component| {
472
/// // ...
473
/// });
474
///
475
/// // ...than this. Always benchmark to validate the difference!
476
/// for component in query.iter() {
477
/// // ...
478
/// }
479
/// }
480
/// #
481
/// # bevy_ecs::system::assert_is_system(system);
482
/// ```
483
///
484
/// [autovectorization]: https://en.wikipedia.org/wiki/Automatic_vectorization
485
pub struct Query<'world, 'state, D: QueryData, F: QueryFilter = ()> {
486
// SAFETY: Must have access to the components registered in `state`.
487
world: UnsafeWorldCell<'world>,
488
state: &'state QueryState<D, F>,
489
last_run: Tick,
490
this_run: Tick,
491
}
492
493
impl<D: ReadOnlyQueryData, F: QueryFilter> Clone for Query<'_, '_, D, F> {
494
fn clone(&self) -> Self {
495
*self
496
}
497
}
498
499
impl<D: ReadOnlyQueryData, F: QueryFilter> Copy for Query<'_, '_, D, F> {}
500
501
impl<D: QueryData, F: QueryFilter> core::fmt::Debug for Query<'_, '_, D, F> {
502
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
503
f.debug_struct("Query")
504
.field("matched_entities", &self.iter().count())
505
.field("state", &self.state)
506
.field("last_run", &self.last_run)
507
.field("this_run", &self.this_run)
508
.field("world", &self.world)
509
.finish()
510
}
511
}
512
513
impl<'w, 's, D: QueryData, F: QueryFilter> Query<'w, 's, D, F> {
514
/// Creates a new query.
515
///
516
/// # Safety
517
///
518
/// * This will create a query that could violate memory safety rules. Make sure that this is only
519
/// called in ways that ensure the queries have unique mutable access.
520
/// * `world` must be the world used to create `state`.
521
#[inline]
522
pub(crate) unsafe fn new(
523
world: UnsafeWorldCell<'w>,
524
state: &'s QueryState<D, F>,
525
last_run: Tick,
526
this_run: Tick,
527
) -> Self {
528
Self {
529
world,
530
state,
531
last_run,
532
this_run,
533
}
534
}
535
536
/// Returns another `Query` from this that fetches the read-only version of the query items.
537
///
538
/// For example, `Query<(&mut D1, &D2, &mut D3), With<F>>` will become `Query<(&D1, &D2, &D3), With<F>>`.
539
/// This can be useful when working around the borrow checker,
540
/// or reusing functionality between systems via functions that accept query types.
541
///
542
/// # See also
543
///
544
/// [`into_readonly`](Self::into_readonly) for a version that consumes the `Query` to return one with the full `'world` lifetime.
545
pub fn as_readonly(&self) -> Query<'_, 's, D::ReadOnly, F> {
546
// SAFETY: The reborrowed query is converted to read-only, so it cannot perform mutable access,
547
// and the original query is held with a shared borrow, so it cannot perform mutable access either.
548
unsafe { self.reborrow_unsafe() }.into_readonly()
549
}
550
551
/// Returns another `Query` from this does not return any data, which can be faster.
552
fn as_nop(&self) -> Query<'_, 's, NopWorldQuery<D>, F> {
553
let new_state = self.state.as_nop();
554
// SAFETY:
555
// - The reborrowed query is converted to read-only, so it cannot perform mutable access,
556
// and the original query is held with a shared borrow, so it cannot perform mutable access either.
557
// Note that although `NopWorldQuery` itself performs *no* access and could soundly alias a mutable query,
558
// it has the original `QueryState::component_access` and could be `transmute`d to a read-only query.
559
// - The world matches because it was the same one used to construct self.
560
unsafe { Query::new(self.world, new_state, self.last_run, self.this_run) }
561
}
562
563
/// Returns another `Query` from this that fetches the read-only version of the query items.
564
///
565
/// For example, `Query<(&mut D1, &D2, &mut D3), With<F>>` will become `Query<(&D1, &D2, &D3), With<F>>`.
566
/// This can be useful when working around the borrow checker,
567
/// or reusing functionality between systems via functions that accept query types.
568
///
569
/// # See also
570
///
571
/// [`as_readonly`](Self::as_readonly) for a version that borrows the `Query` instead of consuming it.
572
pub fn into_readonly(self) -> Query<'w, 's, D::ReadOnly, F> {
573
let new_state = self.state.as_readonly();
574
// SAFETY:
575
// - This is memory safe because it turns the query immutable.
576
// - The world matches because it was the same one used to construct self.
577
unsafe { Query::new(self.world, new_state, self.last_run, self.this_run) }
578
}
579
580
/// Returns a new `Query` reborrowing the access from this one. The current query will be unusable
581
/// while the new one exists.
582
///
583
/// # Example
584
///
585
/// For example this allows to call other methods or other systems that require an owned `Query` without
586
/// completely giving up ownership of it.
587
///
588
/// ```
589
/// # use bevy_ecs::prelude::*;
590
/// #
591
/// # #[derive(Component)]
592
/// # struct ComponentA;
593
///
594
/// fn helper_system(query: Query<&ComponentA>) { /* ... */}
595
///
596
/// fn system(mut query: Query<&ComponentA>) {
597
/// helper_system(query.reborrow());
598
/// // Can still use query here:
599
/// for component in &query {
600
/// // ...
601
/// }
602
/// }
603
/// ```
604
pub fn reborrow(&mut self) -> Query<'_, 's, D, F> {
605
// SAFETY: this query is exclusively borrowed while the new one exists, so
606
// no overlapping access can occur.
607
unsafe { self.reborrow_unsafe() }
608
}
609
610
/// Returns a new `Query` reborrowing the access from this one.
611
/// The current query will still be usable while the new one exists, but must not be used in a way that violates aliasing.
612
///
613
/// # Safety
614
///
615
/// This function makes it possible to violate Rust's aliasing guarantees.
616
/// You must make sure this call does not result in a mutable or shared reference to a component with a mutable reference.
617
///
618
/// # See also
619
///
620
/// - [`reborrow`](Self::reborrow) for the safe versions.
621
pub unsafe fn reborrow_unsafe(&self) -> Query<'_, 's, D, F> {
622
// SAFETY:
623
// - This is memory safe because the caller ensures that there are no conflicting references.
624
// - The world matches because it was the same one used to construct self.
625
unsafe { self.copy_unsafe() }
626
}
627
628
/// Returns a new `Query` copying the access from this one.
629
/// The current query will still be usable while the new one exists, but must not be used in a way that violates aliasing.
630
///
631
/// # Safety
632
///
633
/// This function makes it possible to violate Rust's aliasing guarantees.
634
/// You must make sure this call does not result in a mutable or shared reference to a component with a mutable reference.
635
///
636
/// # See also
637
///
638
/// - [`reborrow_unsafe`](Self::reborrow_unsafe) for a safer version that constrains the returned `'w` lifetime to the length of the borrow.
639
unsafe fn copy_unsafe(&self) -> Query<'w, 's, D, F> {
640
// SAFETY:
641
// - This is memory safe because the caller ensures that there are no conflicting references.
642
// - The world matches because it was the same one used to construct self.
643
unsafe { Query::new(self.world, self.state, self.last_run, self.this_run) }
644
}
645
646
/// Returns an [`Iterator`] over the read-only query items.
647
///
648
/// This iterator is always guaranteed to return results from each matching entity once and only once.
649
/// Iteration order is not guaranteed.
650
///
651
/// # Example
652
///
653
/// Here, the `report_names_system` iterates over the `Player` component of every entity that contains it:
654
///
655
/// ```
656
/// # use bevy_ecs::prelude::*;
657
/// #
658
/// # #[derive(Component)]
659
/// # struct Player { name: String }
660
/// #
661
/// fn report_names_system(query: Query<&Player>) {
662
/// for player in &query {
663
/// println!("Say hello to {}!", player.name);
664
/// }
665
/// }
666
/// # bevy_ecs::system::assert_is_system(report_names_system);
667
/// ```
668
///
669
/// # See also
670
///
671
/// [`iter_mut`](Self::iter_mut) for mutable query items.
672
#[inline]
673
pub fn iter(&self) -> QueryIter<'_, 's, D::ReadOnly, F> {
674
self.as_readonly().into_iter()
675
}
676
677
/// Returns an [`Iterator`] over the query items.
678
///
679
/// This iterator is always guaranteed to return results from each matching entity once and only once.
680
/// Iteration order is not guaranteed.
681
///
682
/// # Example
683
///
684
/// Here, the `gravity_system` updates the `Velocity` component of every entity that contains it:
685
///
686
/// ```
687
/// # use bevy_ecs::prelude::*;
688
/// #
689
/// # #[derive(Component)]
690
/// # struct Velocity { x: f32, y: f32, z: f32 }
691
/// fn gravity_system(mut query: Query<&mut Velocity>) {
692
/// const DELTA: f32 = 1.0 / 60.0;
693
/// for mut velocity in &mut query {
694
/// velocity.y -= 9.8 * DELTA;
695
/// }
696
/// }
697
/// # bevy_ecs::system::assert_is_system(gravity_system);
698
/// ```
699
///
700
/// # See also
701
///
702
/// [`iter`](Self::iter) for read-only query items.
703
#[inline]
704
pub fn iter_mut(&mut self) -> QueryIter<'_, 's, D, F> {
705
self.reborrow().into_iter()
706
}
707
708
/// Returns a [`QueryCombinationIter`] over all combinations of `K` read-only query items without repetition.
709
///
710
/// This iterator is always guaranteed to return results from each unique pair of matching entities.
711
/// Iteration order is not guaranteed.
712
///
713
/// # Example
714
///
715
/// ```
716
/// # use bevy_ecs::prelude::*;
717
/// # #[derive(Component)]
718
/// # struct ComponentA;
719
/// #
720
/// fn some_system(query: Query<&ComponentA>) {
721
/// for [a1, a2] in query.iter_combinations() {
722
/// // ...
723
/// }
724
/// }
725
/// ```
726
///
727
/// # See also
728
///
729
/// - [`iter_combinations_mut`](Self::iter_combinations_mut) for mutable query item combinations.
730
/// - [`iter_combinations_inner`](Self::iter_combinations_inner) for mutable query item combinations with the full `'world` lifetime.
731
#[inline]
732
pub fn iter_combinations<const K: usize>(
733
&self,
734
) -> QueryCombinationIter<'_, 's, D::ReadOnly, F, K> {
735
self.as_readonly().iter_combinations_inner()
736
}
737
738
/// Returns a [`QueryCombinationIter`] over all combinations of `K` query items without repetition.
739
///
740
/// This iterator is always guaranteed to return results from each unique pair of matching entities.
741
/// Iteration order is not guaranteed.
742
///
743
/// # Example
744
///
745
/// ```
746
/// # use bevy_ecs::prelude::*;
747
/// # #[derive(Component)]
748
/// # struct ComponentA;
749
/// fn some_system(mut query: Query<&mut ComponentA>) {
750
/// let mut combinations = query.iter_combinations_mut();
751
/// while let Some([mut a1, mut a2]) = combinations.fetch_next() {
752
/// // mutably access components data
753
/// }
754
/// }
755
/// ```
756
///
757
/// # See also
758
///
759
/// - [`iter_combinations`](Self::iter_combinations) for read-only query item combinations.
760
/// - [`iter_combinations_inner`](Self::iter_combinations_inner) for mutable query item combinations with the full `'world` lifetime.
761
#[inline]
762
pub fn iter_combinations_mut<const K: usize>(
763
&mut self,
764
) -> QueryCombinationIter<'_, 's, D, F, K> {
765
self.reborrow().iter_combinations_inner()
766
}
767
768
/// Returns a [`QueryCombinationIter`] over all combinations of `K` query items without repetition.
769
/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
770
///
771
/// This iterator is always guaranteed to return results from each unique pair of matching entities.
772
/// Iteration order is not guaranteed.
773
///
774
/// # Example
775
///
776
/// ```
777
/// # use bevy_ecs::prelude::*;
778
/// # #[derive(Component)]
779
/// # struct ComponentA;
780
/// fn some_system(query: Query<&mut ComponentA>) {
781
/// let mut combinations = query.iter_combinations_inner();
782
/// while let Some([mut a1, mut a2]) = combinations.fetch_next() {
783
/// // mutably access components data
784
/// }
785
/// }
786
/// ```
787
///
788
/// # See also
789
///
790
/// - [`iter_combinations`](Self::iter_combinations) for read-only query item combinations.
791
/// - [`iter_combinations_mut`](Self::iter_combinations_mut) for mutable query item combinations.
792
#[inline]
793
pub fn iter_combinations_inner<const K: usize>(self) -> QueryCombinationIter<'w, 's, D, F, K> {
794
// SAFETY: `self.world` has permission to access the required components.
795
unsafe { QueryCombinationIter::new(self.world, self.state, self.last_run, self.this_run) }
796
}
797
798
/// Returns an [`Iterator`] over the read-only query items generated from an [`Entity`] list.
799
///
800
/// Items are returned in the order of the list of entities, and may not be unique if the input
801
/// doesn't guarantee uniqueness. Entities that don't match the query are skipped.
802
///
803
/// # Example
804
///
805
/// ```
806
/// # use bevy_ecs::prelude::*;
807
/// # #[derive(Component)]
808
/// # struct Counter {
809
/// # value: i32
810
/// # }
811
/// #
812
/// // A component containing an entity list.
813
/// #[derive(Component)]
814
/// struct Friends {
815
/// list: Vec<Entity>,
816
/// }
817
///
818
/// fn system(
819
/// friends_query: Query<&Friends>,
820
/// counter_query: Query<&Counter>,
821
/// ) {
822
/// for friends in &friends_query {
823
/// for counter in counter_query.iter_many(&friends.list) {
824
/// println!("Friend's counter: {}", counter.value);
825
/// }
826
/// }
827
/// }
828
/// # bevy_ecs::system::assert_is_system(system);
829
/// ```
830
///
831
/// # See also
832
///
833
/// - [`iter_many_mut`](Self::iter_many_mut) to get mutable query items.
834
/// - [`iter_many_inner`](Self::iter_many_inner) to get mutable query items with the full `'world` lifetime.
835
#[inline]
836
pub fn iter_many<EntityList: IntoIterator<Item: EntityEquivalent>>(
837
&self,
838
entities: EntityList,
839
) -> QueryManyIter<'_, 's, D::ReadOnly, F, EntityList::IntoIter> {
840
self.as_readonly().iter_many_inner(entities)
841
}
842
843
/// Returns an iterator over the query items generated from an [`Entity`] list.
844
///
845
/// Items are returned in the order of the list of entities, and may not be unique if the input
846
/// doesn't guarantee uniqueness. Entities that don't match the query are skipped.
847
///
848
/// # Examples
849
///
850
/// ```
851
/// # use bevy_ecs::prelude::*;
852
/// #[derive(Component)]
853
/// struct Counter {
854
/// value: i32
855
/// }
856
///
857
/// #[derive(Component)]
858
/// struct Friends {
859
/// list: Vec<Entity>,
860
/// }
861
///
862
/// fn system(
863
/// friends_query: Query<&Friends>,
864
/// mut counter_query: Query<&mut Counter>,
865
/// ) {
866
/// for friends in &friends_query {
867
/// let mut iter = counter_query.iter_many_mut(&friends.list);
868
/// while let Some(mut counter) = iter.fetch_next() {
869
/// println!("Friend's counter: {}", counter.value);
870
/// counter.value += 1;
871
/// }
872
/// }
873
/// }
874
/// # bevy_ecs::system::assert_is_system(system);
875
/// ```
876
/// # See also
877
///
878
/// - [`iter_many`](Self::iter_many) to get read-only query items.
879
/// - [`iter_many_inner`](Self::iter_many_inner) to get mutable query items with the full `'world` lifetime.
880
#[inline]
881
pub fn iter_many_mut<EntityList: IntoIterator<Item: EntityEquivalent>>(
882
&mut self,
883
entities: EntityList,
884
) -> QueryManyIter<'_, 's, D, F, EntityList::IntoIter> {
885
self.reborrow().iter_many_inner(entities)
886
}
887
888
/// Returns an iterator over the query items generated from an [`Entity`] list.
889
/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
890
///
891
/// Items are returned in the order of the list of entities, and may not be unique if the input
892
/// doesn't guarantee uniqueness. Entities that don't match the query are skipped.
893
///
894
/// # See also
895
///
896
/// - [`iter_many`](Self::iter_many) to get read-only query items.
897
/// - [`iter_many_mut`](Self::iter_many_mut) to get mutable query items.
898
#[inline]
899
pub fn iter_many_inner<EntityList: IntoIterator<Item: EntityEquivalent>>(
900
self,
901
entities: EntityList,
902
) -> QueryManyIter<'w, 's, D, F, EntityList::IntoIter> {
903
// SAFETY: `self.world` has permission to access the required components.
904
unsafe {
905
QueryManyIter::new(
906
self.world,
907
self.state,
908
entities,
909
self.last_run,
910
self.this_run,
911
)
912
}
913
}
914
915
/// Returns an [`Iterator`] over the unique read-only query items generated from an [`EntitySet`].
916
///
917
/// Items are returned in the order of the list of entities. Entities that don't match the query are skipped.
918
///
919
/// # Example
920
///
921
/// ```
922
/// # use bevy_ecs::{prelude::*, entity::{EntitySet, UniqueEntityIter}};
923
/// # use core::slice;
924
/// # #[derive(Component)]
925
/// # struct Counter {
926
/// # value: i32
927
/// # }
928
/// #
929
/// // `Friends` ensures that it only lists unique entities.
930
/// #[derive(Component)]
931
/// struct Friends {
932
/// unique_list: Vec<Entity>,
933
/// }
934
///
935
/// impl<'a> IntoIterator for &'a Friends {
936
///
937
/// type Item = &'a Entity;
938
/// type IntoIter = UniqueEntityIter<slice::Iter<'a, Entity>>;
939
///
940
/// fn into_iter(self) -> Self::IntoIter {
941
/// // SAFETY: `Friends` ensures that it unique_list contains only unique entities.
942
/// unsafe { UniqueEntityIter::from_iterator_unchecked(self.unique_list.iter()) }
943
/// }
944
/// }
945
///
946
/// fn system(
947
/// friends_query: Query<&Friends>,
948
/// counter_query: Query<&Counter>,
949
/// ) {
950
/// for friends in &friends_query {
951
/// for counter in counter_query.iter_many_unique(friends) {
952
/// println!("Friend's counter: {:?}", counter.value);
953
/// }
954
/// }
955
/// }
956
/// # bevy_ecs::system::assert_is_system(system);
957
/// ```
958
///
959
/// # See also
960
///
961
/// - [`iter_many_unique_mut`](Self::iter_many_unique_mut) to get mutable query items.
962
/// - [`iter_many_unique_inner`](Self::iter_many_unique_inner) to get with the actual "inner" world lifetime.
963
#[inline]
964
pub fn iter_many_unique<EntityList: EntitySet>(
965
&self,
966
entities: EntityList,
967
) -> QueryManyUniqueIter<'_, 's, D::ReadOnly, F, EntityList::IntoIter> {
968
self.as_readonly().iter_many_unique_inner(entities)
969
}
970
971
/// Returns an iterator over the unique query items generated from an [`EntitySet`].
972
///
973
/// Items are returned in the order of the list of entities. Entities that don't match the query are skipped.
974
///
975
/// # Examples
976
///
977
/// ```
978
/// # use bevy_ecs::{prelude::*, entity::{EntitySet, UniqueEntityIter}};
979
/// # use core::slice;
980
/// #[derive(Component)]
981
/// struct Counter {
982
/// value: i32
983
/// }
984
///
985
/// // `Friends` ensures that it only lists unique entities.
986
/// #[derive(Component)]
987
/// struct Friends {
988
/// unique_list: Vec<Entity>,
989
/// }
990
///
991
/// impl<'a> IntoIterator for &'a Friends {
992
/// type Item = &'a Entity;
993
/// type IntoIter = UniqueEntityIter<slice::Iter<'a, Entity>>;
994
///
995
/// fn into_iter(self) -> Self::IntoIter {
996
/// // SAFETY: `Friends` ensures that it unique_list contains only unique entities.
997
/// unsafe { UniqueEntityIter::from_iterator_unchecked(self.unique_list.iter()) }
998
/// }
999
/// }
1000
///
1001
/// fn system(
1002
/// friends_query: Query<&Friends>,
1003
/// mut counter_query: Query<&mut Counter>,
1004
/// ) {
1005
/// for friends in &friends_query {
1006
/// for mut counter in counter_query.iter_many_unique_mut(friends) {
1007
/// println!("Friend's counter: {:?}", counter.value);
1008
/// counter.value += 1;
1009
/// }
1010
/// }
1011
/// }
1012
/// # bevy_ecs::system::assert_is_system(system);
1013
/// ```
1014
/// # See also
1015
///
1016
/// - [`iter_many_unique`](Self::iter_many_unique) to get read-only query items.
1017
/// - [`iter_many_unique_inner`](Self::iter_many_unique_inner) to get with the actual "inner" world lifetime.
1018
#[inline]
1019
pub fn iter_many_unique_mut<EntityList: EntitySet>(
1020
&mut self,
1021
entities: EntityList,
1022
) -> QueryManyUniqueIter<'_, 's, D, F, EntityList::IntoIter> {
1023
self.reborrow().iter_many_unique_inner(entities)
1024
}
1025
1026
/// Returns an iterator over the unique query items generated from an [`EntitySet`].
1027
/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
1028
///
1029
/// Items are returned in the order of the list of entities. Entities that don't match the query are skipped.
1030
///
1031
/// # Examples
1032
///
1033
/// ```
1034
/// # use bevy_ecs::{prelude::*, entity::{EntitySet, UniqueEntityIter}};
1035
/// # use core::slice;
1036
/// #[derive(Component)]
1037
/// struct Counter {
1038
/// value: i32
1039
/// }
1040
///
1041
/// // `Friends` ensures that it only lists unique entities.
1042
/// #[derive(Component)]
1043
/// struct Friends {
1044
/// unique_list: Vec<Entity>,
1045
/// }
1046
///
1047
/// impl<'a> IntoIterator for &'a Friends {
1048
/// type Item = &'a Entity;
1049
/// type IntoIter = UniqueEntityIter<slice::Iter<'a, Entity>>;
1050
///
1051
/// fn into_iter(self) -> Self::IntoIter {
1052
/// // SAFETY: `Friends` ensures that it unique_list contains only unique entities.
1053
/// unsafe { UniqueEntityIter::from_iterator_unchecked(self.unique_list.iter()) }
1054
/// }
1055
/// }
1056
///
1057
/// fn system(
1058
/// friends_query: Query<&Friends>,
1059
/// mut counter_query: Query<&mut Counter>,
1060
/// ) {
1061
/// let friends = friends_query.single().unwrap();
1062
/// for mut counter in counter_query.iter_many_unique_inner(friends) {
1063
/// println!("Friend's counter: {:?}", counter.value);
1064
/// counter.value += 1;
1065
/// }
1066
/// }
1067
/// # bevy_ecs::system::assert_is_system(system);
1068
/// ```
1069
/// # See also
1070
///
1071
/// - [`iter_many_unique`](Self::iter_many_unique) to get read-only query items.
1072
/// - [`iter_many_unique_mut`](Self::iter_many_unique_mut) to get mutable query items.
1073
#[inline]
1074
pub fn iter_many_unique_inner<EntityList: EntitySet>(
1075
self,
1076
entities: EntityList,
1077
) -> QueryManyUniqueIter<'w, 's, D, F, EntityList::IntoIter> {
1078
// SAFETY: `self.world` has permission to access the required components.
1079
unsafe {
1080
QueryManyUniqueIter::new(
1081
self.world,
1082
self.state,
1083
entities,
1084
self.last_run,
1085
self.this_run,
1086
)
1087
}
1088
}
1089
1090
/// Returns an [`Iterator`] over the query items.
1091
///
1092
/// This iterator is always guaranteed to return results from each matching entity once and only once.
1093
/// Iteration order is not guaranteed.
1094
///
1095
/// # Safety
1096
///
1097
/// This function makes it possible to violate Rust's aliasing guarantees.
1098
/// You must make sure this call does not result in multiple mutable references to the same component.
1099
///
1100
/// # See also
1101
///
1102
/// - [`iter`](Self::iter) and [`iter_mut`](Self::iter_mut) for the safe versions.
1103
#[inline]
1104
pub unsafe fn iter_unsafe(&self) -> QueryIter<'_, 's, D, F> {
1105
// SAFETY: The caller promises that this will not result in multiple mutable references.
1106
unsafe { self.reborrow_unsafe() }.into_iter()
1107
}
1108
1109
/// Iterates over all possible combinations of `K` query items without repetition.
1110
///
1111
/// This iterator is always guaranteed to return results from each unique pair of matching entities.
1112
/// Iteration order is not guaranteed.
1113
///
1114
/// # Safety
1115
///
1116
/// This allows aliased mutability.
1117
/// You must make sure this call does not result in multiple mutable references to the same component.
1118
///
1119
/// # See also
1120
///
1121
/// - [`iter_combinations`](Self::iter_combinations) and [`iter_combinations_mut`](Self::iter_combinations_mut) for the safe versions.
1122
#[inline]
1123
pub unsafe fn iter_combinations_unsafe<const K: usize>(
1124
&self,
1125
) -> QueryCombinationIter<'_, 's, D, F, K> {
1126
// SAFETY: The caller promises that this will not result in multiple mutable references.
1127
unsafe { self.reborrow_unsafe() }.iter_combinations_inner()
1128
}
1129
1130
/// Returns an [`Iterator`] over the query items generated from an [`Entity`] list.
1131
///
1132
/// Items are returned in the order of the list of entities, and may not be unique if the input
1133
/// doesnn't guarantee uniqueness. Entities that don't match the query are skipped.
1134
///
1135
/// # Safety
1136
///
1137
/// This allows aliased mutability and does not check for entity uniqueness.
1138
/// You must make sure this call does not result in multiple mutable references to the same component.
1139
/// Particular care must be taken when collecting the data (rather than iterating over it one item at a time) such as via [`Iterator::collect`].
1140
///
1141
/// # See also
1142
///
1143
/// - [`iter_many_mut`](Self::iter_many_mut) to safely access the query items.
1144
pub unsafe fn iter_many_unsafe<EntityList: IntoIterator<Item: EntityEquivalent>>(
1145
&self,
1146
entities: EntityList,
1147
) -> QueryManyIter<'_, 's, D, F, EntityList::IntoIter> {
1148
// SAFETY: The caller promises that this will not result in multiple mutable references.
1149
unsafe { self.reborrow_unsafe() }.iter_many_inner(entities)
1150
}
1151
1152
/// Returns an [`Iterator`] over the unique query items generated from an [`Entity`] list.
1153
///
1154
/// Items are returned in the order of the list of entities. Entities that don't match the query are skipped.
1155
///
1156
/// # Safety
1157
///
1158
/// This allows aliased mutability.
1159
/// You must make sure this call does not result in multiple mutable references to the same component.
1160
///
1161
/// # See also
1162
///
1163
/// - [`iter_many_unique`](Self::iter_many_unique) to get read-only query items.
1164
/// - [`iter_many_unique_mut`](Self::iter_many_unique_mut) to get mutable query items.
1165
/// - [`iter_many_unique_inner`](Self::iter_many_unique_inner) to get with the actual "inner" world lifetime.
1166
pub unsafe fn iter_many_unique_unsafe<EntityList: EntitySet>(
1167
&self,
1168
entities: EntityList,
1169
) -> QueryManyUniqueIter<'_, 's, D, F, EntityList::IntoIter> {
1170
// SAFETY: The caller promises that this will not result in multiple mutable references.
1171
unsafe { self.reborrow_unsafe() }.iter_many_unique_inner(entities)
1172
}
1173
1174
/// Returns a parallel iterator over the query results for the given [`World`].
1175
///
1176
/// This parallel iterator is always guaranteed to return results from each matching entity once and
1177
/// only once. Iteration order and thread assignment is not guaranteed.
1178
///
1179
/// If the `multithreaded` feature is disabled, iterating with this operates identically to [`Iterator::for_each`]
1180
/// on [`QueryIter`].
1181
///
1182
/// This can only be called for read-only queries, see [`par_iter_mut`] for write-queries.
1183
///
1184
/// Note that you must use the `for_each` method to iterate over the
1185
/// results, see [`par_iter_mut`] for an example.
1186
///
1187
/// [`par_iter_mut`]: Self::par_iter_mut
1188
/// [`World`]: crate::world::World
1189
#[inline]
1190
pub fn par_iter(&self) -> QueryParIter<'_, 's, D::ReadOnly, F> {
1191
self.as_readonly().par_iter_inner()
1192
}
1193
1194
/// Returns a parallel iterator over the query results for the given [`World`].
1195
///
1196
/// This parallel iterator is always guaranteed to return results from each matching entity once and
1197
/// only once. Iteration order and thread assignment is not guaranteed.
1198
///
1199
/// If the `multithreaded` feature is disabled, iterating with this operates identically to [`Iterator::for_each`]
1200
/// on [`QueryIter`].
1201
///
1202
/// This can only be called for mutable queries, see [`par_iter`] for read-only-queries.
1203
///
1204
/// # Example
1205
///
1206
/// Here, the `gravity_system` updates the `Velocity` component of every entity that contains it:
1207
///
1208
/// ```
1209
/// # use bevy_ecs::prelude::*;
1210
/// #
1211
/// # #[derive(Component)]
1212
/// # struct Velocity { x: f32, y: f32, z: f32 }
1213
/// fn gravity_system(mut query: Query<&mut Velocity>) {
1214
/// const DELTA: f32 = 1.0 / 60.0;
1215
/// query.par_iter_mut().for_each(|mut velocity| {
1216
/// velocity.y -= 9.8 * DELTA;
1217
/// });
1218
/// }
1219
/// # bevy_ecs::system::assert_is_system(gravity_system);
1220
/// ```
1221
///
1222
/// [`par_iter`]: Self::par_iter
1223
/// [`World`]: crate::world::World
1224
#[inline]
1225
pub fn par_iter_mut(&mut self) -> QueryParIter<'_, 's, D, F> {
1226
self.reborrow().par_iter_inner()
1227
}
1228
1229
/// Returns a parallel iterator over the query results for the given [`World`](crate::world::World).
1230
/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
1231
///
1232
/// This parallel iterator is always guaranteed to return results from each matching entity once and
1233
/// only once. Iteration order and thread assignment is not guaranteed.
1234
///
1235
/// If the `multithreaded` feature is disabled, iterating with this operates identically to [`Iterator::for_each`]
1236
/// on [`QueryIter`].
1237
///
1238
/// # Example
1239
///
1240
/// Here, the `gravity_system` updates the `Velocity` component of every entity that contains it:
1241
///
1242
/// ```
1243
/// # use bevy_ecs::prelude::*;
1244
/// #
1245
/// # #[derive(Component)]
1246
/// # struct Velocity { x: f32, y: f32, z: f32 }
1247
/// fn gravity_system(query: Query<&mut Velocity>) {
1248
/// const DELTA: f32 = 1.0 / 60.0;
1249
/// query.par_iter_inner().for_each(|mut velocity| {
1250
/// velocity.y -= 9.8 * DELTA;
1251
/// });
1252
/// }
1253
/// # bevy_ecs::system::assert_is_system(gravity_system);
1254
/// ```
1255
#[inline]
1256
pub fn par_iter_inner(self) -> QueryParIter<'w, 's, D, F> {
1257
QueryParIter {
1258
world: self.world,
1259
state: self.state,
1260
last_run: self.last_run,
1261
this_run: self.this_run,
1262
batching_strategy: BatchingStrategy::new(),
1263
}
1264
}
1265
1266
/// Returns a parallel iterator over the read-only query items generated from an [`Entity`] list.
1267
///
1268
/// Entities that don't match the query are skipped. Iteration order and thread assignment is not guaranteed.
1269
///
1270
/// If the `multithreaded` feature is disabled, iterating with this operates identically to [`Iterator::for_each`]
1271
/// on [`QueryManyIter`].
1272
///
1273
/// This can only be called for read-only queries. To avoid potential aliasing, there is no `par_iter_many_mut` equivalent.
1274
/// See [`par_iter_many_unique_mut`] for an alternative using [`EntitySet`].
1275
///
1276
/// Note that you must use the `for_each` method to iterate over the
1277
/// results, see [`par_iter_mut`] for an example.
1278
///
1279
/// [`par_iter_many_unique_mut`]: Self::par_iter_many_unique_mut
1280
/// [`par_iter_mut`]: Self::par_iter_mut
1281
#[inline]
1282
pub fn par_iter_many<EntityList: IntoIterator<Item: EntityEquivalent>>(
1283
&self,
1284
entities: EntityList,
1285
) -> QueryParManyIter<'_, 's, D::ReadOnly, F, EntityList::Item> {
1286
QueryParManyIter {
1287
world: self.world,
1288
state: self.state.as_readonly(),
1289
entity_list: entities.into_iter().collect(),
1290
last_run: self.last_run,
1291
this_run: self.this_run,
1292
batching_strategy: BatchingStrategy::new(),
1293
}
1294
}
1295
1296
/// Returns a parallel iterator over the unique read-only query items generated from an [`EntitySet`].
1297
///
1298
/// Entities that don't match the query are skipped. Iteration order and thread assignment is not guaranteed.
1299
///
1300
/// If the `multithreaded` feature is disabled, iterating with this operates identically to [`Iterator::for_each`]
1301
/// on [`QueryManyUniqueIter`].
1302
///
1303
/// This can only be called for read-only queries, see [`par_iter_many_unique_mut`] for write-queries.
1304
///
1305
/// Note that you must use the `for_each` method to iterate over the
1306
/// results, see [`par_iter_mut`] for an example.
1307
///
1308
/// [`par_iter_many_unique_mut`]: Self::par_iter_many_unique_mut
1309
/// [`par_iter_mut`]: Self::par_iter_mut
1310
#[inline]
1311
pub fn par_iter_many_unique<EntityList: EntitySet<Item: Sync>>(
1312
&self,
1313
entities: EntityList,
1314
) -> QueryParManyUniqueIter<'_, 's, D::ReadOnly, F, EntityList::Item> {
1315
QueryParManyUniqueIter {
1316
world: self.world,
1317
state: self.state.as_readonly(),
1318
entity_list: entities.into_iter().collect(),
1319
last_run: self.last_run,
1320
this_run: self.this_run,
1321
batching_strategy: BatchingStrategy::new(),
1322
}
1323
}
1324
1325
/// Returns a parallel iterator over the unique query items generated from an [`EntitySet`].
1326
///
1327
/// Entities that don't match the query are skipped. Iteration order and thread assignment is not guaranteed.
1328
///
1329
/// If the `multithreaded` feature is disabled, iterating with this operates identically to [`Iterator::for_each`]
1330
/// on [`QueryManyUniqueIter`].
1331
///
1332
/// This can only be called for mutable queries, see [`par_iter_many_unique`] for read-only-queries.
1333
///
1334
/// Note that you must use the `for_each` method to iterate over the
1335
/// results, see [`par_iter_mut`] for an example.
1336
///
1337
/// [`par_iter_many_unique`]: Self::par_iter_many_unique
1338
/// [`par_iter_mut`]: Self::par_iter_mut
1339
#[inline]
1340
pub fn par_iter_many_unique_mut<EntityList: EntitySet<Item: Sync>>(
1341
&mut self,
1342
entities: EntityList,
1343
) -> QueryParManyUniqueIter<'_, 's, D, F, EntityList::Item> {
1344
QueryParManyUniqueIter {
1345
world: self.world,
1346
state: self.state,
1347
entity_list: entities.into_iter().collect(),
1348
last_run: self.last_run,
1349
this_run: self.this_run,
1350
batching_strategy: BatchingStrategy::new(),
1351
}
1352
}
1353
1354
/// Returns the read-only query item for the given [`Entity`].
1355
///
1356
/// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.
1357
///
1358
/// This is always guaranteed to run in `O(1)` time.
1359
///
1360
/// # Example
1361
///
1362
/// Here, `get` is used to retrieve the exact query item of the entity specified by the `SelectedCharacter` resource.
1363
///
1364
/// ```
1365
/// # use bevy_ecs::prelude::*;
1366
/// #
1367
/// # #[derive(Resource)]
1368
/// # struct SelectedCharacter { entity: Entity }
1369
/// # #[derive(Component)]
1370
/// # struct Character { name: String }
1371
/// #
1372
/// fn print_selected_character_name_system(
1373
/// query: Query<&Character>,
1374
/// selection: Res<SelectedCharacter>
1375
/// )
1376
/// {
1377
/// if let Ok(selected_character) = query.get(selection.entity) {
1378
/// println!("{}", selected_character.name);
1379
/// }
1380
/// }
1381
/// # bevy_ecs::system::assert_is_system(print_selected_character_name_system);
1382
/// ```
1383
///
1384
/// # See also
1385
///
1386
/// - [`get_mut`](Self::get_mut) to get a mutable query item.
1387
#[inline]
1388
pub fn get(&self, entity: Entity) -> Result<ROQueryItem<'_, 's, D>, QueryEntityError> {
1389
self.as_readonly().get_inner(entity)
1390
}
1391
1392
/// Returns the read-only query items for the given array of [`Entity`].
1393
///
1394
/// The returned query items are in the same order as the input.
1395
/// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.
1396
/// The elements of the array do not need to be unique, unlike `get_many_mut`.
1397
///
1398
/// # Examples
1399
///
1400
/// ```
1401
/// use bevy_ecs::prelude::*;
1402
/// use bevy_ecs::query::QueryEntityError;
1403
///
1404
/// #[derive(Component, PartialEq, Debug)]
1405
/// struct A(usize);
1406
///
1407
/// let mut world = World::new();
1408
/// let entity_vec: Vec<Entity> = (0..3).map(|i| world.spawn(A(i)).id()).collect();
1409
/// let entities: [Entity; 3] = entity_vec.try_into().unwrap();
1410
///
1411
/// world.spawn(A(73));
1412
///
1413
/// let mut query_state = world.query::<&A>();
1414
/// let query = query_state.query(&world);
1415
///
1416
/// let component_values = query.get_many(entities).unwrap();
1417
///
1418
/// assert_eq!(component_values, [&A(0), &A(1), &A(2)]);
1419
///
1420
/// let wrong_entity = Entity::from_raw_u32(365).unwrap();
1421
///
1422
/// assert_eq!(
1423
/// match query.get_many([wrong_entity]).unwrap_err() {
1424
/// QueryEntityError::EntityDoesNotExist(error) => error.entity,
1425
/// _ => panic!(),
1426
/// },
1427
/// wrong_entity
1428
/// );
1429
/// ```
1430
///
1431
/// # See also
1432
///
1433
/// - [`get_many_mut`](Self::get_many_mut) to get mutable query items.
1434
/// - [`get_many_unique`](Self::get_many_unique) to only handle unique inputs.
1435
#[inline]
1436
pub fn get_many<const N: usize>(
1437
&self,
1438
entities: [Entity; N],
1439
) -> Result<[ROQueryItem<'_, 's, D>; N], QueryEntityError> {
1440
// Note that we call a separate `*_inner` method from `get_many_mut`
1441
// because we don't need to check for duplicates.
1442
self.as_readonly().get_many_inner(entities)
1443
}
1444
1445
/// Returns the read-only query items for the given [`UniqueEntityArray`].
1446
///
1447
/// The returned query items are in the same order as the input.
1448
/// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.
1449
///
1450
/// # Examples
1451
///
1452
/// ```
1453
/// use bevy_ecs::{prelude::*, query::QueryEntityError, entity::{EntitySetIterator, UniqueEntityArray, UniqueEntityVec}};
1454
///
1455
/// #[derive(Component, PartialEq, Debug)]
1456
/// struct A(usize);
1457
///
1458
/// let mut world = World::new();
1459
/// let entity_set: UniqueEntityVec = world.spawn_batch((0..3).map(A)).collect_set();
1460
/// let entity_set: UniqueEntityArray<3> = entity_set.try_into().unwrap();
1461
///
1462
/// world.spawn(A(73));
1463
///
1464
/// let mut query_state = world.query::<&A>();
1465
/// let query = query_state.query(&world);
1466
///
1467
/// let component_values = query.get_many_unique(entity_set).unwrap();
1468
///
1469
/// assert_eq!(component_values, [&A(0), &A(1), &A(2)]);
1470
///
1471
/// let wrong_entity = Entity::from_raw_u32(365).unwrap();
1472
///
1473
/// assert_eq!(
1474
/// match query.get_many_unique(UniqueEntityArray::from([wrong_entity])).unwrap_err() {
1475
/// QueryEntityError::EntityDoesNotExist(error) => error.entity,
1476
/// _ => panic!(),
1477
/// },
1478
/// wrong_entity
1479
/// );
1480
/// ```
1481
///
1482
/// # See also
1483
///
1484
/// - [`get_many_unique_mut`](Self::get_many_mut) to get mutable query items.
1485
/// - [`get_many`](Self::get_many) to handle inputs with duplicates.
1486
#[inline]
1487
pub fn get_many_unique<const N: usize>(
1488
&self,
1489
entities: UniqueEntityArray<N>,
1490
) -> Result<[ROQueryItem<'_, 's, D>; N], QueryEntityError> {
1491
self.as_readonly().get_many_unique_inner(entities)
1492
}
1493
1494
/// Returns the query item for the given [`Entity`].
1495
///
1496
/// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.
1497
///
1498
/// This is always guaranteed to run in `O(1)` time.
1499
///
1500
/// # Example
1501
///
1502
/// Here, `get_mut` is used to retrieve the exact query item of the entity specified by the `PoisonedCharacter` resource.
1503
///
1504
/// ```
1505
/// # use bevy_ecs::prelude::*;
1506
/// #
1507
/// # #[derive(Resource)]
1508
/// # struct PoisonedCharacter { character_id: Entity }
1509
/// # #[derive(Component)]
1510
/// # struct Health(u32);
1511
/// #
1512
/// fn poison_system(mut query: Query<&mut Health>, poisoned: Res<PoisonedCharacter>) {
1513
/// if let Ok(mut health) = query.get_mut(poisoned.character_id) {
1514
/// health.0 -= 1;
1515
/// }
1516
/// }
1517
/// # bevy_ecs::system::assert_is_system(poison_system);
1518
/// ```
1519
///
1520
/// # See also
1521
///
1522
/// - [`get`](Self::get) to get a read-only query item.
1523
#[inline]
1524
pub fn get_mut(&mut self, entity: Entity) -> Result<D::Item<'_, 's>, QueryEntityError> {
1525
self.reborrow().get_inner(entity)
1526
}
1527
1528
/// Returns the query item for the given [`Entity`].
1529
/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
1530
///
1531
/// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.
1532
///
1533
/// This is always guaranteed to run in `O(1)` time.
1534
///
1535
/// # See also
1536
///
1537
/// - [`get_mut`](Self::get_mut) to get the item using a mutable borrow of the [`Query`].
1538
#[inline]
1539
pub fn get_inner(self, entity: Entity) -> Result<D::Item<'w, 's>, QueryEntityError> {
1540
// SAFETY: system runs without conflicts with other systems.
1541
// same-system queries have runtime borrow checks when they conflict
1542
unsafe {
1543
let location = self
1544
.world
1545
.entities()
1546
.get(entity)
1547
.ok_or(EntityDoesNotExistError::new(entity, self.world.entities()))?;
1548
if !self
1549
.state
1550
.matched_archetypes
1551
.contains(location.archetype_id.index())
1552
{
1553
return Err(QueryEntityError::QueryDoesNotMatch(
1554
entity,
1555
location.archetype_id,
1556
));
1557
}
1558
let archetype = self
1559
.world
1560
.archetypes()
1561
.get(location.archetype_id)
1562
.debug_checked_unwrap();
1563
let mut fetch = D::init_fetch(
1564
self.world,
1565
&self.state.fetch_state,
1566
self.last_run,
1567
self.this_run,
1568
);
1569
let mut filter = F::init_fetch(
1570
self.world,
1571
&self.state.filter_state,
1572
self.last_run,
1573
self.this_run,
1574
);
1575
1576
let table = self
1577
.world
1578
.storages()
1579
.tables
1580
.get(location.table_id)
1581
.debug_checked_unwrap();
1582
D::set_archetype(&mut fetch, &self.state.fetch_state, archetype, table);
1583
F::set_archetype(&mut filter, &self.state.filter_state, archetype, table);
1584
1585
if F::filter_fetch(
1586
&self.state.filter_state,
1587
&mut filter,
1588
entity,
1589
location.table_row,
1590
) {
1591
Ok(D::fetch(
1592
&self.state.fetch_state,
1593
&mut fetch,
1594
entity,
1595
location.table_row,
1596
))
1597
} else {
1598
Err(QueryEntityError::QueryDoesNotMatch(
1599
entity,
1600
location.archetype_id,
1601
))
1602
}
1603
}
1604
}
1605
1606
/// Returns the query items for the given array of [`Entity`].
1607
///
1608
/// The returned query items are in the same order as the input.
1609
/// In case of a nonexisting entity, duplicate entities or mismatched component, a [`QueryEntityError`] is returned instead.
1610
///
1611
/// # Examples
1612
///
1613
/// ```
1614
/// use bevy_ecs::prelude::*;
1615
/// use bevy_ecs::query::QueryEntityError;
1616
///
1617
/// #[derive(Component, PartialEq, Debug)]
1618
/// struct A(usize);
1619
///
1620
/// let mut world = World::new();
1621
///
1622
/// let entities: Vec<Entity> = (0..3).map(|i| world.spawn(A(i)).id()).collect();
1623
/// let entities: [Entity; 3] = entities.try_into().unwrap();
1624
///
1625
/// world.spawn(A(73));
1626
/// let wrong_entity = Entity::from_raw_u32(57).unwrap();
1627
/// let invalid_entity = world.spawn_empty().id();
1628
///
1629
///
1630
/// let mut query_state = world.query::<&mut A>();
1631
/// let mut query = query_state.query_mut(&mut world);
1632
///
1633
/// let mut mutable_component_values = query.get_many_mut(entities).unwrap();
1634
///
1635
/// for mut a in &mut mutable_component_values {
1636
/// a.0 += 5;
1637
/// }
1638
///
1639
/// let component_values = query.get_many(entities).unwrap();
1640
///
1641
/// assert_eq!(component_values, [&A(5), &A(6), &A(7)]);
1642
///
1643
/// assert_eq!(
1644
/// match query
1645
/// .get_many_mut([wrong_entity])
1646
/// .unwrap_err()
1647
/// {
1648
/// QueryEntityError::EntityDoesNotExist(error) => error.entity,
1649
/// _ => panic!(),
1650
/// },
1651
/// wrong_entity
1652
/// );
1653
/// assert_eq!(
1654
/// match query
1655
/// .get_many_mut([invalid_entity])
1656
/// .unwrap_err()
1657
/// {
1658
/// QueryEntityError::QueryDoesNotMatch(entity, _) => entity,
1659
/// _ => panic!(),
1660
/// },
1661
/// invalid_entity
1662
/// );
1663
/// assert_eq!(
1664
/// query
1665
/// .get_many_mut([entities[0], entities[0]])
1666
/// .unwrap_err(),
1667
/// QueryEntityError::AliasedMutability(entities[0])
1668
/// );
1669
/// ```
1670
/// # See also
1671
///
1672
/// - [`get_many`](Self::get_many) to get read-only query items without checking for duplicate entities.
1673
#[inline]
1674
pub fn get_many_mut<const N: usize>(
1675
&mut self,
1676
entities: [Entity; N],
1677
) -> Result<[D::Item<'_, 's>; N], QueryEntityError> {
1678
self.reborrow().get_many_mut_inner(entities)
1679
}
1680
1681
/// Returns the query items for the given [`UniqueEntityArray`].
1682
///
1683
/// The returned query items are in the same order as the input.
1684
/// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.
1685
///
1686
/// # Examples
1687
///
1688
/// ```
1689
/// use bevy_ecs::{prelude::*, query::QueryEntityError, entity::{EntitySetIterator, UniqueEntityArray, UniqueEntityVec}};
1690
///
1691
/// #[derive(Component, PartialEq, Debug)]
1692
/// struct A(usize);
1693
///
1694
/// let mut world = World::new();
1695
///
1696
/// let entity_set: UniqueEntityVec = world.spawn_batch((0..3).map(A)).collect_set();
1697
/// let entity_set: UniqueEntityArray<3> = entity_set.try_into().unwrap();
1698
///
1699
/// world.spawn(A(73));
1700
/// let wrong_entity = Entity::from_raw_u32(57).unwrap();
1701
/// let invalid_entity = world.spawn_empty().id();
1702
///
1703
///
1704
/// let mut query_state = world.query::<&mut A>();
1705
/// let mut query = query_state.query_mut(&mut world);
1706
///
1707
/// let mut mutable_component_values = query.get_many_unique_mut(entity_set).unwrap();
1708
///
1709
/// for mut a in &mut mutable_component_values {
1710
/// a.0 += 5;
1711
/// }
1712
///
1713
/// let component_values = query.get_many_unique(entity_set).unwrap();
1714
///
1715
/// assert_eq!(component_values, [&A(5), &A(6), &A(7)]);
1716
///
1717
/// assert_eq!(
1718
/// match query
1719
/// .get_many_unique_mut(UniqueEntityArray::from([wrong_entity]))
1720
/// .unwrap_err()
1721
/// {
1722
/// QueryEntityError::EntityDoesNotExist(error) => error.entity,
1723
/// _ => panic!(),
1724
/// },
1725
/// wrong_entity
1726
/// );
1727
/// assert_eq!(
1728
/// match query
1729
/// .get_many_unique_mut(UniqueEntityArray::from([invalid_entity]))
1730
/// .unwrap_err()
1731
/// {
1732
/// QueryEntityError::QueryDoesNotMatch(entity, _) => entity,
1733
/// _ => panic!(),
1734
/// },
1735
/// invalid_entity
1736
/// );
1737
/// ```
1738
/// # See also
1739
///
1740
/// - [`get_many_unique`](Self::get_many) to get read-only query items.
1741
#[inline]
1742
pub fn get_many_unique_mut<const N: usize>(
1743
&mut self,
1744
entities: UniqueEntityArray<N>,
1745
) -> Result<[D::Item<'_, 's>; N], QueryEntityError> {
1746
self.reborrow().get_many_unique_inner(entities)
1747
}
1748
1749
/// Returns the query items for the given array of [`Entity`].
1750
/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
1751
///
1752
/// The returned query items are in the same order as the input.
1753
/// In case of a nonexisting entity, duplicate entities or mismatched component, a [`QueryEntityError`] is returned instead.
1754
///
1755
/// # See also
1756
///
1757
/// - [`get_many`](Self::get_many) to get read-only query items without checking for duplicate entities.
1758
/// - [`get_many_mut`](Self::get_many_mut) to get items using a mutable reference.
1759
/// - [`get_many_inner`](Self::get_many_mut_inner) to get read-only query items with the actual "inner" world lifetime.
1760
#[inline]
1761
pub fn get_many_mut_inner<const N: usize>(
1762
self,
1763
entities: [Entity; N],
1764
) -> Result<[D::Item<'w, 's>; N], QueryEntityError> {
1765
// Verify that all entities are unique
1766
for i in 0..N {
1767
for j in 0..i {
1768
if entities[i] == entities[j] {
1769
return Err(QueryEntityError::AliasedMutability(entities[i]));
1770
}
1771
}
1772
}
1773
// SAFETY: All entities are unique, so the results don't alias.
1774
unsafe { self.get_many_impl(entities) }
1775
}
1776
1777
/// Returns the query items for the given array of [`Entity`].
1778
/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
1779
///
1780
/// The returned query items are in the same order as the input.
1781
/// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.
1782
///
1783
/// # See also
1784
///
1785
/// - [`get_many`](Self::get_many) to get read-only query items without checking for duplicate entities.
1786
/// - [`get_many_mut`](Self::get_many_mut) to get items using a mutable reference.
1787
/// - [`get_many_mut_inner`](Self::get_many_mut_inner) to get mutable query items with the actual "inner" world lifetime.
1788
#[inline]
1789
pub fn get_many_inner<const N: usize>(
1790
self,
1791
entities: [Entity; N],
1792
) -> Result<[D::Item<'w, 's>; N], QueryEntityError>
1793
where
1794
D: ReadOnlyQueryData,
1795
{
1796
// SAFETY: The query results are read-only, so they don't conflict if there are duplicate entities.
1797
unsafe { self.get_many_impl(entities) }
1798
}
1799
1800
/// Returns the query items for the given [`UniqueEntityArray`].
1801
/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
1802
///
1803
/// The returned query items are in the same order as the input.
1804
/// In case of a nonexisting entity, duplicate entities or mismatched component, a [`QueryEntityError`] is returned instead.
1805
///
1806
/// # See also
1807
///
1808
/// - [`get_many_unique`](Self::get_many_unique) to get read-only query items without checking for duplicate entities.
1809
/// - [`get_many_unique_mut`](Self::get_many_unique_mut) to get items using a mutable reference.
1810
#[inline]
1811
pub fn get_many_unique_inner<const N: usize>(
1812
self,
1813
entities: UniqueEntityArray<N>,
1814
) -> Result<[D::Item<'w, 's>; N], QueryEntityError> {
1815
// SAFETY: All entities are unique, so the results don't alias.
1816
unsafe { self.get_many_impl(entities.into_inner()) }
1817
}
1818
1819
/// Returns the query items for the given array of [`Entity`].
1820
/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
1821
///
1822
/// # Safety
1823
///
1824
/// The caller must ensure that the query data returned for the entities does not conflict,
1825
/// either because they are all unique or because the data is read-only.
1826
unsafe fn get_many_impl<const N: usize>(
1827
self,
1828
entities: [Entity; N],
1829
) -> Result<[D::Item<'w, 's>; N], QueryEntityError> {
1830
let mut values = [(); N].map(|_| MaybeUninit::uninit());
1831
1832
for (value, entity) in core::iter::zip(&mut values, entities) {
1833
// SAFETY: The caller asserts that the results don't alias
1834
let item = unsafe { self.copy_unsafe() }.get_inner(entity)?;
1835
*value = MaybeUninit::new(item);
1836
}
1837
1838
// SAFETY: Each value has been fully initialized.
1839
Ok(values.map(|x| unsafe { x.assume_init() }))
1840
}
1841
1842
/// Returns the query item for the given [`Entity`].
1843
///
1844
/// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.
1845
///
1846
/// This is always guaranteed to run in `O(1)` time.
1847
///
1848
/// # Safety
1849
///
1850
/// This function makes it possible to violate Rust's aliasing guarantees.
1851
/// You must make sure this call does not result in multiple mutable references to the same component.
1852
///
1853
/// # See also
1854
///
1855
/// - [`get_mut`](Self::get_mut) for the safe version.
1856
#[inline]
1857
pub unsafe fn get_unchecked(
1858
&self,
1859
entity: Entity,
1860
) -> Result<D::Item<'_, 's>, QueryEntityError> {
1861
// SAFETY: The caller promises that this will not result in multiple mutable references.
1862
unsafe { self.reborrow_unsafe() }.get_inner(entity)
1863
}
1864
1865
/// Returns a single read-only query item when there is exactly one entity matching the query.
1866
///
1867
/// If the number of query items is not exactly one, a [`QuerySingleError`] is returned instead.
1868
///
1869
/// # Example
1870
///
1871
/// ```
1872
/// # use bevy_ecs::prelude::*;
1873
/// # use bevy_ecs::query::QuerySingleError;
1874
/// # #[derive(Component)]
1875
/// # struct PlayerScore(i32);
1876
/// fn player_scoring_system(query: Query<&PlayerScore>) {
1877
/// match query.single() {
1878
/// Ok(PlayerScore(score)) => {
1879
/// println!("Score: {}", score);
1880
/// }
1881
/// Err(QuerySingleError::NoEntities(_)) => {
1882
/// println!("Error: There is no player!");
1883
/// }
1884
/// Err(QuerySingleError::MultipleEntities(_)) => {
1885
/// println!("Error: There is more than one player!");
1886
/// }
1887
/// }
1888
/// }
1889
/// # bevy_ecs::system::assert_is_system(player_scoring_system);
1890
/// ```
1891
///
1892
/// # See also
1893
///
1894
/// - [`single_mut`](Self::single_mut) to get the mutable query item.
1895
#[inline]
1896
pub fn single(&self) -> Result<ROQueryItem<'_, 's, D>, QuerySingleError> {
1897
self.as_readonly().single_inner()
1898
}
1899
1900
/// Returns a single query item when there is exactly one entity matching the query.
1901
///
1902
/// If the number of query items is not exactly one, a [`QuerySingleError`] is returned instead.
1903
///
1904
/// # Example
1905
///
1906
/// ```
1907
/// # use bevy_ecs::prelude::*;
1908
/// #
1909
/// # #[derive(Component)]
1910
/// # struct Player;
1911
/// # #[derive(Component)]
1912
/// # struct Health(u32);
1913
/// #
1914
/// fn regenerate_player_health_system(mut query: Query<&mut Health, With<Player>>) {
1915
/// let mut health = query.single_mut().expect("Error: Could not find a single player.");
1916
/// health.0 += 1;
1917
/// }
1918
/// # bevy_ecs::system::assert_is_system(regenerate_player_health_system);
1919
/// ```
1920
///
1921
/// # See also
1922
///
1923
/// - [`single`](Self::single) to get the read-only query item.
1924
#[inline]
1925
pub fn single_mut(&mut self) -> Result<D::Item<'_, 's>, QuerySingleError> {
1926
self.reborrow().single_inner()
1927
}
1928
1929
/// Returns a single query item when there is exactly one entity matching the query.
1930
/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
1931
///
1932
/// If the number of query items is not exactly one, a [`QuerySingleError`] is returned instead.
1933
///
1934
/// # Example
1935
///
1936
/// ```
1937
/// # use bevy_ecs::prelude::*;
1938
/// #
1939
/// # #[derive(Component)]
1940
/// # struct Player;
1941
/// # #[derive(Component)]
1942
/// # struct Health(u32);
1943
/// #
1944
/// fn regenerate_player_health_system(query: Query<&mut Health, With<Player>>) {
1945
/// let mut health = query.single_inner().expect("Error: Could not find a single player.");
1946
/// health.0 += 1;
1947
/// }
1948
/// # bevy_ecs::system::assert_is_system(regenerate_player_health_system);
1949
/// ```
1950
///
1951
/// # See also
1952
///
1953
/// - [`single`](Self::single) to get the read-only query item.
1954
/// - [`single_mut`](Self::single_mut) to get the mutable query item.
1955
/// - [`single_inner`](Self::single_inner) for the panicking version.
1956
#[inline]
1957
pub fn single_inner(self) -> Result<D::Item<'w, 's>, QuerySingleError> {
1958
let mut query = self.into_iter();
1959
let first = query.next();
1960
let extra = query.next().is_some();
1961
1962
match (first, extra) {
1963
(Some(r), false) => Ok(r),
1964
(None, _) => Err(QuerySingleError::NoEntities(DebugName::type_name::<Self>())),
1965
(Some(_), _) => Err(QuerySingleError::MultipleEntities(DebugName::type_name::<
1966
Self,
1967
>())),
1968
}
1969
}
1970
1971
/// Returns `true` if there are no query items.
1972
///
1973
/// This is equivalent to `self.iter().next().is_none()`, and thus the worst case runtime will be `O(n)`
1974
/// where `n` is the number of *potential* matches. This can be notably expensive for queries that rely
1975
/// on non-archetypal filters such as [`Added`], [`Changed`] or [`Spawned`] which must individually check
1976
/// each query result for a match.
1977
///
1978
/// # Example
1979
///
1980
/// Here, the score is increased only if an entity with a `Player` component is present in the world:
1981
///
1982
/// ```
1983
/// # use bevy_ecs::prelude::*;
1984
/// #
1985
/// # #[derive(Component)]
1986
/// # struct Player;
1987
/// # #[derive(Resource)]
1988
/// # struct Score(u32);
1989
/// fn update_score_system(query: Query<(), With<Player>>, mut score: ResMut<Score>) {
1990
/// if !query.is_empty() {
1991
/// score.0 += 1;
1992
/// }
1993
/// }
1994
/// # bevy_ecs::system::assert_is_system(update_score_system);
1995
/// ```
1996
///
1997
/// [`Added`]: crate::query::Added
1998
/// [`Changed`]: crate::query::Changed
1999
/// [`Spawned`]: crate::query::Spawned
2000
#[inline]
2001
pub fn is_empty(&self) -> bool {
2002
self.as_nop().iter().next().is_none()
2003
}
2004
2005
/// Returns `true` if the given [`Entity`] matches the query.
2006
///
2007
/// This is always guaranteed to run in `O(1)` time.
2008
///
2009
/// # Example
2010
///
2011
/// ```
2012
/// # use bevy_ecs::prelude::*;
2013
/// #
2014
/// # #[derive(Component)]
2015
/// # struct InRange;
2016
/// #
2017
/// # #[derive(Resource)]
2018
/// # struct Target {
2019
/// # entity: Entity,
2020
/// # }
2021
/// #
2022
/// fn targeting_system(in_range_query: Query<&InRange>, target: Res<Target>) {
2023
/// if in_range_query.contains(target.entity) {
2024
/// println!("Bam!")
2025
/// }
2026
/// }
2027
/// # bevy_ecs::system::assert_is_system(targeting_system);
2028
/// ```
2029
#[inline]
2030
pub fn contains(&self, entity: Entity) -> bool {
2031
self.as_nop().get(entity).is_ok()
2032
}
2033
2034
/// Counts the number of entities that match the query.
2035
///
2036
/// This is equivalent to `self.iter().count()` but may be more efficient in some cases.
2037
///
2038
/// If [`F::IS_ARCHETYPAL`](QueryFilter::IS_ARCHETYPAL) is `true`,
2039
/// this will do work proportional to the number of matched archetypes or tables, but will not iterate each entity.
2040
/// If it is `false`, it will have to do work for each entity.
2041
///
2042
/// # Example
2043
///
2044
/// ```
2045
/// # use bevy_ecs::prelude::*;
2046
/// #
2047
/// # #[derive(Component)]
2048
/// # struct InRange;
2049
/// #
2050
/// fn targeting_system(in_range_query: Query<&InRange>) {
2051
/// let count = in_range_query.count();
2052
/// println!("{count} targets in range!");
2053
/// }
2054
/// # bevy_ecs::system::assert_is_system(targeting_system);
2055
/// ```
2056
pub fn count(&self) -> usize {
2057
let iter = self.as_nop().into_iter();
2058
if F::IS_ARCHETYPAL {
2059
// For archetypal queries, the `size_hint()` is exact,
2060
// and we can get the count from the archetype and table counts.
2061
iter.size_hint().0
2062
} else {
2063
// If we have non-archetypal filters, we have to check each entity.
2064
iter.count()
2065
}
2066
}
2067
2068
/// Returns a [`QueryLens`] that can be used to construct a new [`Query`] giving more
2069
/// restrictive access to the entities matched by the current query.
2070
///
2071
/// A transmute is valid only if `NewD` has a subset of the read, write, and required access
2072
/// of the current query. A precise description of the access required by each parameter
2073
/// type is given in the table below, but typical uses are to:
2074
/// * Remove components, e.g. `Query<(&A, &B)>` to `Query<&A>`.
2075
/// * Retrieve an existing component with reduced or equal access, e.g. `Query<&mut A>` to `Query<&A>`
2076
/// or `Query<&T>` to `Query<Ref<T>>`.
2077
/// * Add parameters with no new access, for example adding an `Entity` parameter.
2078
///
2079
/// Note that since filter terms are dropped, non-archetypal filters like
2080
/// [`Added`], [`Changed`] and [`Spawned`] will not be respected. To maintain or change filter
2081
/// terms see [`Self::transmute_lens_filtered`].
2082
///
2083
/// |`QueryData` parameter type|Access required|
2084
/// |----|----|
2085
/// |[`Entity`], [`EntityLocation`], [`SpawnDetails`], [`&Archetype`], [`Has<T>`], [`PhantomData<T>`]|No access|
2086
/// |[`EntityMut`]|Read and write access to all components, but no required access|
2087
/// |[`EntityRef`]|Read access to all components, but no required access|
2088
/// |`&T`, [`Ref<T>`]|Read and required access to `T`|
2089
/// |`&mut T`, [`Mut<T>`]|Read, write and required access to `T`|
2090
/// |[`Option<T>`], [`AnyOf<(D, ...)>`]|Read and write access to `T`, but no required access|
2091
/// |Tuples of query data and<br/>`#[derive(QueryData)]` structs|The union of the access of their subqueries|
2092
/// |[`FilteredEntityRef`], [`FilteredEntityMut`]|Determined by the [`QueryBuilder`] used to construct them. Any query can be transmuted to them, and they will receive the access of the source query. When combined with other `QueryData`, they will receive any access of the source query that does not conflict with the other data|
2093
///
2094
/// `transmute_lens` drops filter terms, but [`Self::transmute_lens_filtered`] supports returning a [`QueryLens`] with a new
2095
/// filter type - the access required by filter parameters are as follows.
2096
///
2097
/// |`QueryFilter` parameter type|Access required|
2098
/// |----|----|
2099
/// |[`Added<T>`], [`Changed<T>`]|Read and required access to `T`|
2100
/// |[`With<T>`], [`Without<T>`]|No access|
2101
/// |[`Or<(T, ...)>`]|Read access of the subqueries, but no required access|
2102
/// |Tuples of query filters and `#[derive(QueryFilter)]` structs|The union of the access of their subqueries|
2103
///
2104
/// [`Added`]: crate::query::Added
2105
/// [`Added<T>`]: crate::query::Added
2106
/// [`AnyOf<(D, ...)>`]: crate::query::AnyOf
2107
/// [`&Archetype`]: crate::archetype::Archetype
2108
/// [`Changed`]: crate::query::Changed
2109
/// [`Changed<T>`]: crate::query::Changed
2110
/// [`EntityMut`]: crate::world::EntityMut
2111
/// [`EntityLocation`]: crate::entity::EntityLocation
2112
/// [`EntityRef`]: crate::world::EntityRef
2113
/// [`FilteredEntityRef`]: crate::world::FilteredEntityRef
2114
/// [`FilteredEntityMut`]: crate::world::FilteredEntityMut
2115
/// [`Has<T>`]: crate::query::Has
2116
/// [`Mut<T>`]: crate::world::Mut
2117
/// [`Or<(T, ...)>`]: crate::query::Or
2118
/// [`QueryBuilder`]: crate::query::QueryBuilder
2119
/// [`Ref<T>`]: crate::world::Ref
2120
/// [`SpawnDetails`]: crate::query::SpawnDetails
2121
/// [`Spawned`]: crate::query::Spawned
2122
/// [`With<T>`]: crate::query::With
2123
/// [`Without<T>`]: crate::query::Without
2124
///
2125
/// ## Panics
2126
///
2127
/// This will panic if the access required by `NewD` is not a subset of that required by
2128
/// the original fetch `D`.
2129
///
2130
/// ## Example
2131
///
2132
/// ```rust
2133
/// # use bevy_ecs::prelude::*;
2134
/// # use bevy_ecs::system::QueryLens;
2135
/// #
2136
/// # #[derive(Component)]
2137
/// # struct A(usize);
2138
/// #
2139
/// # #[derive(Component)]
2140
/// # struct B(usize);
2141
/// #
2142
/// # let mut world = World::new();
2143
/// #
2144
/// # world.spawn((A(10), B(5)));
2145
/// #
2146
/// fn reusable_function(lens: &mut QueryLens<&A>) {
2147
/// assert_eq!(lens.query().single().unwrap().0, 10);
2148
/// }
2149
///
2150
/// // We can use the function in a system that takes the exact query.
2151
/// fn system_1(mut query: Query<&A>) {
2152
/// reusable_function(&mut query.as_query_lens());
2153
/// }
2154
///
2155
/// // We can also use it with a query that does not match exactly
2156
/// // by transmuting it.
2157
/// fn system_2(mut query: Query<(&mut A, &B)>) {
2158
/// let mut lens = query.transmute_lens::<&A>();
2159
/// reusable_function(&mut lens);
2160
/// }
2161
///
2162
/// # let mut schedule = Schedule::default();
2163
/// # schedule.add_systems((system_1, system_2));
2164
/// # schedule.run(&mut world);
2165
/// ```
2166
///
2167
/// ### Examples of valid transmutes
2168
///
2169
/// ```rust
2170
/// # use bevy_ecs::{
2171
/// # prelude::*,
2172
/// # archetype::Archetype,
2173
/// # entity::EntityLocation,
2174
/// # query::{QueryData, QueryFilter},
2175
/// # world::{FilteredEntityMut, FilteredEntityRef},
2176
/// # };
2177
/// # use std::marker::PhantomData;
2178
/// #
2179
/// # fn assert_valid_transmute<OldD: QueryData, NewD: QueryData>() {
2180
/// # assert_valid_transmute_filtered::<OldD, (), NewD, ()>();
2181
/// # }
2182
/// #
2183
/// # fn assert_valid_transmute_filtered<OldD: QueryData, OldF: QueryFilter, NewD: QueryData, NewF: QueryFilter>() {
2184
/// # let mut world = World::new();
2185
/// # // Make sure all components in the new query are initialized
2186
/// # let state = world.query_filtered::<NewD, NewF>();
2187
/// # let state = world.query_filtered::<OldD, OldF>();
2188
/// # state.transmute_filtered::<NewD, NewF>(&world);
2189
/// # }
2190
/// #
2191
/// # #[derive(Component)]
2192
/// # struct T;
2193
/// #
2194
/// # #[derive(Component)]
2195
/// # struct U;
2196
/// #
2197
/// # #[derive(Component)]
2198
/// # struct V;
2199
/// #
2200
/// // `&mut T` and `Mut<T>` access the same data and can be transmuted to each other,
2201
/// // `&T` and `Ref<T>` access the same data and can be transmuted to each other,
2202
/// // and mutable versions can be transmuted to read-only versions
2203
/// assert_valid_transmute::<&mut T, &T>();
2204
/// assert_valid_transmute::<&mut T, Mut<T>>();
2205
/// assert_valid_transmute::<Mut<T>, &mut T>();
2206
/// assert_valid_transmute::<&T, Ref<T>>();
2207
/// assert_valid_transmute::<Ref<T>, &T>();
2208
///
2209
/// // The structure can be rearranged, or subqueries dropped
2210
/// assert_valid_transmute::<(&T, &U), &T>();
2211
/// assert_valid_transmute::<((&T, &U), &V), (&T, (&U, &V))>();
2212
/// assert_valid_transmute::<Option<(&T, &U)>, (Option<&T>, Option<&U>)>();
2213
///
2214
/// // Queries with no access can be freely added
2215
/// assert_valid_transmute::<
2216
/// &T,
2217
/// (&T, Entity, EntityLocation, &Archetype, Has<U>, PhantomData<T>),
2218
/// >();
2219
///
2220
/// // Required access can be transmuted to optional,
2221
/// // and optional access can be transmuted to other optional access
2222
/// assert_valid_transmute::<&T, Option<&T>>();
2223
/// assert_valid_transmute::<AnyOf<(&mut T, &mut U)>, Option<&T>>();
2224
/// // Note that removing subqueries from `AnyOf` will result
2225
/// // in an `AnyOf` where all subqueries can yield `None`!
2226
/// assert_valid_transmute::<AnyOf<(&T, &U, &V)>, AnyOf<(&T, &U)>>();
2227
/// assert_valid_transmute::<EntityMut, Option<&mut T>>();
2228
///
2229
/// // Anything can be transmuted to `FilteredEntityRef` or `FilteredEntityMut`
2230
/// // This will create a `FilteredEntityMut` that only has read access to `T`
2231
/// assert_valid_transmute::<&T, FilteredEntityMut>();
2232
/// // This will create a `FilteredEntityMut` that has no access to `T`,
2233
/// // read access to `U`, and write access to `V`.
2234
/// assert_valid_transmute::<(&mut T, &mut U, &mut V), (&mut T, &U, FilteredEntityMut)>();
2235
///
2236
/// // `Added<T>` and `Changed<T>` filters have the same access as `&T` data
2237
/// // Remember that they are only evaluated on the transmuted query, not the original query!
2238
/// assert_valid_transmute_filtered::<Entity, Changed<T>, &T, ()>();
2239
/// assert_valid_transmute_filtered::<&mut T, (), &T, Added<T>>();
2240
/// // Nested inside of an `Or` filter, they have the same access as `Option<&T>`.
2241
/// assert_valid_transmute_filtered::<Option<&T>, (), Entity, Or<(Changed<T>, With<U>)>>();
2242
/// ```
2243
#[track_caller]
2244
pub fn transmute_lens<NewD: QueryData>(&mut self) -> QueryLens<'_, NewD> {
2245
self.transmute_lens_filtered::<NewD, ()>()
2246
}
2247
2248
/// Returns a [`QueryLens`] that can be used to construct a new `Query` giving more restrictive
2249
/// access to the entities matched by the current query.
2250
///
2251
/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
2252
///
2253
/// See [`Self::transmute_lens`] for a description of allowed transmutes.
2254
///
2255
/// ## Panics
2256
///
2257
/// This will panic if `NewD` is not a subset of the original fetch `D`
2258
///
2259
/// ## Example
2260
///
2261
/// ```rust
2262
/// # use bevy_ecs::prelude::*;
2263
/// # use bevy_ecs::system::QueryLens;
2264
/// #
2265
/// # #[derive(Component)]
2266
/// # struct A(usize);
2267
/// #
2268
/// # #[derive(Component)]
2269
/// # struct B(usize);
2270
/// #
2271
/// # let mut world = World::new();
2272
/// #
2273
/// # world.spawn((A(10), B(5)));
2274
/// #
2275
/// fn reusable_function(mut lens: QueryLens<&A>) {
2276
/// assert_eq!(lens.query().single().unwrap().0, 10);
2277
/// }
2278
///
2279
/// // We can use the function in a system that takes the exact query.
2280
/// fn system_1(query: Query<&A>) {
2281
/// reusable_function(query.into_query_lens());
2282
/// }
2283
///
2284
/// // We can also use it with a query that does not match exactly
2285
/// // by transmuting it.
2286
/// fn system_2(query: Query<(&mut A, &B)>) {
2287
/// let mut lens = query.transmute_lens_inner::<&A>();
2288
/// reusable_function(lens);
2289
/// }
2290
///
2291
/// # let mut schedule = Schedule::default();
2292
/// # schedule.add_systems((system_1, system_2));
2293
/// # schedule.run(&mut world);
2294
/// ```
2295
///
2296
/// # See also
2297
///
2298
/// - [`transmute_lens`](Self::transmute_lens) to convert to a lens using a mutable borrow of the [`Query`].
2299
#[track_caller]
2300
pub fn transmute_lens_inner<NewD: QueryData>(self) -> QueryLens<'w, NewD> {
2301
self.transmute_lens_filtered_inner::<NewD, ()>()
2302
}
2303
2304
/// Equivalent to [`Self::transmute_lens`] but also includes a [`QueryFilter`] type.
2305
///
2306
/// See [`Self::transmute_lens`] for a description of allowed transmutes.
2307
///
2308
/// Note that the lens will iterate the same tables and archetypes as the original query. This means that
2309
/// additional archetypal query terms like [`With`](crate::query::With) and [`Without`](crate::query::Without)
2310
/// will not necessarily be respected and non-archetypal terms like [`Added`](crate::query::Added),
2311
/// [`Changed`](crate::query::Changed) and [`Spawned`](crate::query::Spawned) will only be respected if they
2312
/// are in the type signature.
2313
#[track_caller]
2314
pub fn transmute_lens_filtered<NewD: QueryData, NewF: QueryFilter>(
2315
&mut self,
2316
) -> QueryLens<'_, NewD, NewF> {
2317
self.reborrow().transmute_lens_filtered_inner()
2318
}
2319
2320
/// Equivalent to [`Self::transmute_lens_inner`] but also includes a [`QueryFilter`] type.
2321
/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
2322
///
2323
/// See [`Self::transmute_lens`] for a description of allowed transmutes.
2324
///
2325
/// Note that the lens will iterate the same tables and archetypes as the original query. This means that
2326
/// additional archetypal query terms like [`With`](crate::query::With) and [`Without`](crate::query::Without)
2327
/// will not necessarily be respected and non-archetypal terms like [`Added`](crate::query::Added),
2328
/// [`Changed`](crate::query::Changed) and [`Spawned`](crate::query::Spawned) will only be respected if they
2329
/// are in the type signature.
2330
///
2331
/// # See also
2332
///
2333
/// - [`transmute_lens_filtered`](Self::transmute_lens_filtered) to convert to a lens using a mutable borrow of the [`Query`].
2334
#[track_caller]
2335
pub fn transmute_lens_filtered_inner<NewD: QueryData, NewF: QueryFilter>(
2336
self,
2337
) -> QueryLens<'w, NewD, NewF> {
2338
let state = self.state.transmute_filtered::<NewD, NewF>(self.world);
2339
QueryLens {
2340
world: self.world,
2341
state,
2342
last_run: self.last_run,
2343
this_run: self.this_run,
2344
}
2345
}
2346
2347
/// Gets a [`QueryLens`] with the same accesses as the existing query
2348
pub fn as_query_lens(&mut self) -> QueryLens<'_, D> {
2349
self.transmute_lens()
2350
}
2351
2352
/// Gets a [`QueryLens`] with the same accesses as the existing query
2353
///
2354
/// # See also
2355
///
2356
/// - [`as_query_lens`](Self::as_query_lens) to convert to a lens using a mutable borrow of the [`Query`].
2357
pub fn into_query_lens(self) -> QueryLens<'w, D> {
2358
self.transmute_lens_inner()
2359
}
2360
2361
/// Returns a [`QueryLens`] that can be used to get a query with the combined fetch.
2362
///
2363
/// For example, this can take a `Query<&A>` and a `Query<&B>` and return a `Query<(&A, &B)>`.
2364
/// The returned query will only return items with both `A` and `B`. Note that since filters
2365
/// are dropped, non-archetypal filters like `Added`, `Changed` and `Spawned` will not be respected.
2366
/// To maintain or change filter terms see `Self::join_filtered`.
2367
///
2368
/// ## Example
2369
///
2370
/// ```rust
2371
/// # use bevy_ecs::prelude::*;
2372
/// # use bevy_ecs::system::QueryLens;
2373
/// #
2374
/// # #[derive(Component)]
2375
/// # struct Transform;
2376
/// #
2377
/// # #[derive(Component)]
2378
/// # struct Player;
2379
/// #
2380
/// # #[derive(Component)]
2381
/// # struct Enemy;
2382
/// #
2383
/// # let mut world = World::default();
2384
/// # world.spawn((Transform, Player));
2385
/// # world.spawn((Transform, Enemy));
2386
///
2387
/// fn system(
2388
/// mut transforms: Query<&Transform>,
2389
/// mut players: Query<&Player>,
2390
/// mut enemies: Query<&Enemy>
2391
/// ) {
2392
/// let mut players_transforms: QueryLens<(&Transform, &Player)> = transforms.join(&mut players);
2393
/// for (transform, player) in &players_transforms.query() {
2394
/// // do something with a and b
2395
/// }
2396
///
2397
/// let mut enemies_transforms: QueryLens<(&Transform, &Enemy)> = transforms.join(&mut enemies);
2398
/// for (transform, enemy) in &enemies_transforms.query() {
2399
/// // do something with a and b
2400
/// }
2401
/// }
2402
///
2403
/// # let mut schedule = Schedule::default();
2404
/// # schedule.add_systems(system);
2405
/// # schedule.run(&mut world);
2406
/// ```
2407
/// ## Panics
2408
///
2409
/// This will panic if `NewD` is not a subset of the union of the original fetch `Q` and `OtherD`.
2410
///
2411
/// ## Allowed Transmutes
2412
///
2413
/// Like `transmute_lens` the query terms can be changed with some restrictions.
2414
/// See [`Self::transmute_lens`] for more details.
2415
pub fn join<'a, OtherD: QueryData, NewD: QueryData>(
2416
&'a mut self,
2417
other: &'a mut Query<OtherD>,
2418
) -> QueryLens<'a, NewD> {
2419
self.join_filtered(other)
2420
}
2421
2422
/// Returns a [`QueryLens`] that can be used to get a query with the combined fetch.
2423
/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
2424
///
2425
/// For example, this can take a `Query<&A>` and a `Query<&B>` and return a `Query<(&A, &B)>`.
2426
/// The returned query will only return items with both `A` and `B`. Note that since filters
2427
/// are dropped, non-archetypal filters like `Added`, `Changed` and `Spawned` will not be respected.
2428
/// To maintain or change filter terms see `Self::join_filtered`.
2429
///
2430
/// ## Panics
2431
///
2432
/// This will panic if `NewD` is not a subset of the union of the original fetch `Q` and `OtherD`.
2433
///
2434
/// ## Allowed Transmutes
2435
///
2436
/// Like `transmute_lens` the query terms can be changed with some restrictions.
2437
/// See [`Self::transmute_lens`] for more details.
2438
///
2439
/// # See also
2440
///
2441
/// - [`join`](Self::join) to join using a mutable borrow of the [`Query`].
2442
pub fn join_inner<OtherD: QueryData, NewD: QueryData>(
2443
self,
2444
other: Query<'w, '_, OtherD>,
2445
) -> QueryLens<'w, NewD> {
2446
self.join_filtered_inner(other)
2447
}
2448
2449
/// Equivalent to [`Self::join`] but also includes a [`QueryFilter`] type.
2450
///
2451
/// Note that the lens with iterate a subset of the original queries' tables
2452
/// and archetypes. This means that additional archetypal query terms like
2453
/// `With` and `Without` will not necessarily be respected and non-archetypal
2454
/// terms like `Added`, `Changed` and `Spawned` will only be respected if they
2455
/// are in the type signature.
2456
pub fn join_filtered<
2457
'a,
2458
OtherD: QueryData,
2459
OtherF: QueryFilter,
2460
NewD: QueryData,
2461
NewF: QueryFilter,
2462
>(
2463
&'a mut self,
2464
other: &'a mut Query<OtherD, OtherF>,
2465
) -> QueryLens<'a, NewD, NewF> {
2466
self.reborrow().join_filtered_inner(other.reborrow())
2467
}
2468
2469
/// Equivalent to [`Self::join_inner`] but also includes a [`QueryFilter`] type.
2470
/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.
2471
///
2472
/// Note that the lens with iterate a subset of the original queries' tables
2473
/// and archetypes. This means that additional archetypal query terms like
2474
/// `With` and `Without` will not necessarily be respected and non-archetypal
2475
/// terms like `Added`, `Changed` and `Spawned` will only be respected if they
2476
/// are in the type signature.
2477
///
2478
/// # See also
2479
///
2480
/// - [`join_filtered`](Self::join_filtered) to join using a mutable borrow of the [`Query`].
2481
pub fn join_filtered_inner<
2482
OtherD: QueryData,
2483
OtherF: QueryFilter,
2484
NewD: QueryData,
2485
NewF: QueryFilter,
2486
>(
2487
self,
2488
other: Query<'w, '_, OtherD, OtherF>,
2489
) -> QueryLens<'w, NewD, NewF> {
2490
let state = self
2491
.state
2492
.join_filtered::<OtherD, OtherF, NewD, NewF>(self.world, other.state);
2493
QueryLens {
2494
world: self.world,
2495
state,
2496
last_run: self.last_run,
2497
this_run: self.this_run,
2498
}
2499
}
2500
}
2501
2502
impl<'w, 's, D: QueryData, F: QueryFilter> IntoIterator for Query<'w, 's, D, F> {
2503
type Item = D::Item<'w, 's>;
2504
type IntoIter = QueryIter<'w, 's, D, F>;
2505
2506
fn into_iter(self) -> Self::IntoIter {
2507
// SAFETY:
2508
// - `self.world` has permission to access the required components.
2509
// - We consume the query, so mutable queries cannot alias.
2510
// Read-only queries are `Copy`, but may alias themselves.
2511
unsafe { QueryIter::new(self.world, self.state, self.last_run, self.this_run) }
2512
}
2513
}
2514
2515
impl<'w, 's, D: QueryData, F: QueryFilter> IntoIterator for &'w Query<'_, 's, D, F> {
2516
type Item = ROQueryItem<'w, 's, D>;
2517
type IntoIter = QueryIter<'w, 's, D::ReadOnly, F>;
2518
2519
fn into_iter(self) -> Self::IntoIter {
2520
self.iter()
2521
}
2522
}
2523
2524
impl<'w, 's, D: QueryData, F: QueryFilter> IntoIterator for &'w mut Query<'_, 's, D, F> {
2525
type Item = D::Item<'w, 's>;
2526
type IntoIter = QueryIter<'w, 's, D, F>;
2527
2528
fn into_iter(self) -> Self::IntoIter {
2529
self.iter_mut()
2530
}
2531
}
2532
2533
impl<'w, 's, D: ReadOnlyQueryData, F: QueryFilter> Query<'w, 's, D, F> {
2534
/// Returns an [`Iterator`] over the query items, with the actual "inner" world lifetime.
2535
///
2536
/// This can only return immutable data (mutable data will be cast to an immutable form).
2537
/// See [`Self::iter_mut`] for queries that contain at least one mutable component.
2538
///
2539
/// # Example
2540
///
2541
/// Here, the `report_names_system` iterates over the `Player` component of every entity
2542
/// that contains it:
2543
///
2544
/// ```
2545
/// # use bevy_ecs::prelude::*;
2546
/// #
2547
/// # #[derive(Component)]
2548
/// # struct Player { name: String }
2549
/// #
2550
/// fn report_names_system(query: Query<&Player>) {
2551
/// for player in &query {
2552
/// println!("Say hello to {}!", player.name);
2553
/// }
2554
/// }
2555
/// # bevy_ecs::system::assert_is_system(report_names_system);
2556
/// ```
2557
#[inline]
2558
pub fn iter_inner(&self) -> QueryIter<'w, 's, D::ReadOnly, F> {
2559
(*self).into_iter()
2560
}
2561
}
2562
2563
/// Type returned from [`Query::transmute_lens`] containing the new [`QueryState`].
2564
///
2565
/// Call [`query`](QueryLens::query) or [`into`](Into::into) to construct the resulting [`Query`]
2566
pub struct QueryLens<'w, Q: QueryData, F: QueryFilter = ()> {
2567
world: UnsafeWorldCell<'w>,
2568
state: QueryState<Q, F>,
2569
last_run: Tick,
2570
this_run: Tick,
2571
}
2572
2573
impl<'w, Q: QueryData, F: QueryFilter> QueryLens<'w, Q, F> {
2574
/// Create a [`Query`] from the underlying [`QueryState`].
2575
pub fn query(&mut self) -> Query<'_, '_, Q, F> {
2576
Query {
2577
world: self.world,
2578
state: &self.state,
2579
last_run: self.last_run,
2580
this_run: self.this_run,
2581
}
2582
}
2583
}
2584
2585
impl<'w, Q: ReadOnlyQueryData, F: QueryFilter> QueryLens<'w, Q, F> {
2586
/// Create a [`Query`] from the underlying [`QueryState`].
2587
/// This returns results with the actual "inner" world lifetime,
2588
/// so it may only be used with read-only queries to prevent mutable aliasing.
2589
pub fn query_inner(&self) -> Query<'w, '_, Q, F> {
2590
Query {
2591
world: self.world,
2592
state: &self.state,
2593
last_run: self.last_run,
2594
this_run: self.this_run,
2595
}
2596
}
2597
}
2598
2599
impl<'w, 's, Q: QueryData, F: QueryFilter> From<&'s mut QueryLens<'w, Q, F>>
2600
for Query<'s, 's, Q, F>
2601
{
2602
fn from(value: &'s mut QueryLens<'w, Q, F>) -> Query<'s, 's, Q, F> {
2603
value.query()
2604
}
2605
}
2606
2607
impl<'w, 'q, Q: QueryData, F: QueryFilter> From<&'q mut Query<'w, '_, Q, F>>
2608
for QueryLens<'q, Q, F>
2609
{
2610
fn from(value: &'q mut Query<'w, '_, Q, F>) -> QueryLens<'q, Q, F> {
2611
value.transmute_lens_filtered()
2612
}
2613
}
2614
2615
/// [System parameter] that provides access to single entity's components, much like [`Query::single`]/[`Query::single_mut`].
2616
///
2617
/// This [`SystemParam`](crate::system::SystemParam) fails validation if zero or more than one matching entity exists.
2618
/// This will cause the system to be skipped, according to the rules laid out in [`SystemParamValidationError`](crate::system::SystemParamValidationError).
2619
///
2620
/// Use [`Option<Single<D, F>>`] instead if zero or one matching entities can exist.
2621
///
2622
/// See [`Query`] for more details.
2623
///
2624
/// [System parameter]: crate::system::SystemParam
2625
///
2626
/// # Example
2627
/// ```
2628
/// # use bevy_ecs::prelude::*;
2629
/// #[derive(Component)]
2630
/// struct Boss {
2631
/// health: f32
2632
/// };
2633
///
2634
/// fn hurt_boss(mut boss: Single<&mut Boss>) {
2635
/// boss.health -= 4.0;
2636
/// }
2637
/// ```
2638
/// Note that because [`Single`] implements [`Deref`] and [`DerefMut`], methods and fields like `health` can be accessed directly.
2639
/// You can also access the underlying data manually, by calling `.deref`/`.deref_mut`, or by using the `*` operator.
2640
pub struct Single<'w, 's, D: QueryData, F: QueryFilter = ()> {
2641
pub(crate) item: D::Item<'w, 's>,
2642
pub(crate) _filter: PhantomData<F>,
2643
}
2644
2645
impl<'w, 's, D: QueryData, F: QueryFilter> Deref for Single<'w, 's, D, F> {
2646
type Target = D::Item<'w, 's>;
2647
2648
fn deref(&self) -> &Self::Target {
2649
&self.item
2650
}
2651
}
2652
2653
impl<'w, 's, D: QueryData, F: QueryFilter> DerefMut for Single<'w, 's, D, F> {
2654
fn deref_mut(&mut self) -> &mut Self::Target {
2655
&mut self.item
2656
}
2657
}
2658
2659
impl<'w, 's, D: QueryData, F: QueryFilter> Single<'w, 's, D, F> {
2660
/// Returns the inner item with ownership.
2661
pub fn into_inner(self) -> D::Item<'w, 's> {
2662
self.item
2663
}
2664
}
2665
2666
/// [System parameter] that works very much like [`Query`] except it always contains at least one matching entity.
2667
///
2668
/// This [`SystemParam`](crate::system::SystemParam) fails validation if no matching entities exist.
2669
/// This will cause the system to be skipped, according to the rules laid out in [`SystemParamValidationError`](crate::system::SystemParamValidationError).
2670
///
2671
/// Much like [`Query::is_empty`] the worst case runtime will be `O(n)` where `n` is the number of *potential* matches.
2672
/// This can be notably expensive for queries that rely on non-archetypal filters such as [`Added`](crate::query::Added),
2673
/// [`Changed`](crate::query::Changed) of [`Spawned`](crate::query::Spawned) which must individually check each query
2674
/// result for a match.
2675
///
2676
/// See [`Query`] for more details.
2677
///
2678
/// [System parameter]: crate::system::SystemParam
2679
pub struct Populated<'w, 's, D: QueryData, F: QueryFilter = ()>(pub(crate) Query<'w, 's, D, F>);
2680
2681
impl<'w, 's, D: QueryData, F: QueryFilter> Deref for Populated<'w, 's, D, F> {
2682
type Target = Query<'w, 's, D, F>;
2683
2684
fn deref(&self) -> &Self::Target {
2685
&self.0
2686
}
2687
}
2688
2689
impl<D: QueryData, F: QueryFilter> DerefMut for Populated<'_, '_, D, F> {
2690
fn deref_mut(&mut self) -> &mut Self::Target {
2691
&mut self.0
2692
}
2693
}
2694
2695
impl<'w, 's, D: QueryData, F: QueryFilter> Populated<'w, 's, D, F> {
2696
/// Returns the inner item with ownership.
2697
pub fn into_inner(self) -> Query<'w, 's, D, F> {
2698
self.0
2699
}
2700
}
2701
2702
impl<'w, 's, D: QueryData, F: QueryFilter> IntoIterator for Populated<'w, 's, D, F> {
2703
type Item = <Query<'w, 's, D, F> as IntoIterator>::Item;
2704
2705
type IntoIter = <Query<'w, 's, D, F> as IntoIterator>::IntoIter;
2706
2707
fn into_iter(self) -> Self::IntoIter {
2708
self.0.into_iter()
2709
}
2710
}
2711
2712
impl<'a, 'w, 's, D: QueryData, F: QueryFilter> IntoIterator for &'a Populated<'w, 's, D, F> {
2713
type Item = <&'a Query<'w, 's, D, F> as IntoIterator>::Item;
2714
2715
type IntoIter = <&'a Query<'w, 's, D, F> as IntoIterator>::IntoIter;
2716
2717
fn into_iter(self) -> Self::IntoIter {
2718
self.deref().into_iter()
2719
}
2720
}
2721
2722
impl<'a, 'w, 's, D: QueryData, F: QueryFilter> IntoIterator for &'a mut Populated<'w, 's, D, F> {
2723
type Item = <&'a mut Query<'w, 's, D, F> as IntoIterator>::Item;
2724
2725
type IntoIter = <&'a mut Query<'w, 's, D, F> as IntoIterator>::IntoIter;
2726
2727
fn into_iter(self) -> Self::IntoIter {
2728
self.deref_mut().into_iter()
2729
}
2730
}
2731
2732
#[cfg(test)]
2733
mod tests {
2734
use crate::{prelude::*, query::QueryEntityError};
2735
use alloc::vec::Vec;
2736
2737
#[test]
2738
fn get_many_uniqueness() {
2739
let mut world = World::new();
2740
2741
let entities: Vec<Entity> = (0..10).map(|_| world.spawn_empty().id()).collect();
2742
2743
let mut query_state = world.query::<Entity>();
2744
2745
// It's best to test get_many_mut_inner directly, as it is shared
2746
// We don't care about aliased mutability for the read-only equivalent
2747
2748
// SAFETY: Query does not access world data.
2749
assert!(query_state
2750
.query_mut(&mut world)
2751
.get_many_mut_inner::<10>(entities.clone().try_into().unwrap())
2752
.is_ok());
2753
2754
assert_eq!(
2755
query_state
2756
.query_mut(&mut world)
2757
.get_many_mut_inner([entities[0], entities[0]])
2758
.unwrap_err(),
2759
QueryEntityError::AliasedMutability(entities[0])
2760
);
2761
2762
assert_eq!(
2763
query_state
2764
.query_mut(&mut world)
2765
.get_many_mut_inner([entities[0], entities[1], entities[0]])
2766
.unwrap_err(),
2767
QueryEntityError::AliasedMutability(entities[0])
2768
);
2769
2770
assert_eq!(
2771
query_state
2772
.query_mut(&mut world)
2773
.get_many_mut_inner([entities[9], entities[9]])
2774
.unwrap_err(),
2775
QueryEntityError::AliasedMutability(entities[9])
2776
);
2777
}
2778
}
2779
2780