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