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