use bevy_utils::prelude::DebugName;12use crate::{3batching::BatchingStrategy,4change_detection::Tick,5entity::{Entity, EntityEquivalent, EntitySet, UniqueEntityArray},6query::{7ArchetypeFilter, ContiguousQueryData, DebugCheckedUnwrap, NopWorldQuery,8QueryCombinationIter, QueryContiguousIter, QueryData, QueryEntityError, QueryFilter,9QueryIter, QueryManyIter, QueryManyUniqueIter, QueryParIter, QueryParManyIter,10QueryParManyUniqueIter, QuerySingleError, QueryState, ROQueryItem, ReadOnlyQueryData,11},12world::unsafe_world_cell::UnsafeWorldCell,13};14use core::{15marker::PhantomData,16mem::MaybeUninit,17ops::{Deref, DerefMut},18};1920/// 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::SystemParam37/// [`Component`]: crate::component::Component38/// [`World`]: crate::world::World39/// [entity identifiers]: Entity40/// [components]: crate::component::Component41///42/// # Similar parameters43///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::SystemParam53/// [`Option<Single>`]: Single54///55/// # System parameter declaration56///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 access61///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,E027787/// # 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 filtering99///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` tuples123///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 are127/// 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 to154/// 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 access181///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 access200///201/// A component can be made optional by wrapping it into an [`Option`]. In the following example, a202/// 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 will215/// // 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 optional225/// components, you may be interested in using [`AnyOf`].226///227/// [performance]: #performance228/// [`AnyOf`]: crate::query::AnyOf229///230/// ## Disjoint queries231///232/// A system cannot contain two queries that break Rust's mutability rules, or else it will panic233/// when initialized. This can often be fixed with the [`Without`] filter, which makes the queries234/// disjoint.235///236/// In the following example, the two queries can mutably access the same `&mut Health` component237/// 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_panic241/// # 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 entity263/// 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 in288/// [`ParamSet`].289///290/// [`Without`]: crate::query::Without291/// [`ParamSet`]: crate::system::ParamSet292///293/// ## Whole Entity Access294///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_panic315/// # 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 with321/// // `&mut ComponentA` in the same query, it creates a conflict because `EntityRef` could read322/// // `&ComponentA` while `&mut ComponentA` attempts to modify it - violating Rust's borrowing323/// // 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 and333/// parallelization of the system, but it enables systems to gain mutable access to other334/// 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 only346/// // modifies entities that *don't* have `ComponentA`. Because neither query will access the same347/// // 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 never359/// coexist with mutable access. [`With`] / [`Without`] filters can guarantee this by keeping the360/// queries on completely separate entities.361///362/// [`EntityRef`]: crate::world::EntityRef363/// [`With`]: crate::query::With364///365/// # Accessing query items366///367/// The following table summarizes the behavior of safe methods that can be used to get query368/// 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::iter385/// [`iter_mut`]: Self::iter_mut386/// [`for_each`]: #iteratorfor_each387/// [`par_iter`]: Self::par_iter388/// [`par_iter_mut`]: Self::par_iter_mut389/// [`iter_many`]: Self::iter_many390/// [`iter_many_unique`]: Self::iter_many_unique391/// [`iter_many_mut`]: Self::iter_many_mut392/// [`iter_combinations`]: Self::iter_combinations393/// [`iter_combinations_mut`]: Self::iter_combinations_mut394/// [`single_mut`]: Self::single_mut395/// [`get`]: Self::get396/// [`get_mut`]: Self::get_mut397/// [`get_many`]: Self::get_many398/// [`get_many_unique`]: Self::get_many_unique399/// [`get_many_mut`]: Self::get_many_mut400///401/// # Performance402///403/// Creating a `Query` is a low-cost constant operation. Iterating it, on the other hand, fetches404/// 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 at407/// least one of the accesses is mutable. Because of this, it is recommended for queries to only408/// 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 of411/// entities that can be fetched. Systems that access fewer kinds of entities are more likely to be412/// parallelized by the scheduler.413///414/// On the other hand, be careful using optional components (`Option<&ComponentA>`) and415/// [`EntityRef`] because they broaden the amount of entities kinds that can be accessed. This is416/// especially true of a query that _only_ fetches optional components or [`EntityRef`], as the417/// query would iterate over all entities in the world.418///419/// There are two types of [component storage types]: [`Table`] and [`SparseSet`]. [`Table`] offers420/// 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 and424/// 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> is431/// 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::StorageType448/// [`Table`]: crate::storage::Table449/// [`SparseSet`]: crate::storage::SparseSet450/// [binomial coefficient]: https://en.wikipedia.org/wiki/Binomial_coefficient451/// [`Or`]: crate::query::Or452/// [`Added`]: crate::query::Added453/// [`Changed`]: crate::query::Changed454/// [`Spawned`]: crate::query::Spawned455///456/// # `Iterator::for_each`457///458/// The `for_each` methods appear to be generally faster than `for`-loops when run on worlds with459/// high archetype fragmentation, and may enable additional optimizations like [autovectorization]. It460/// 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/// ```rust464/// # 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_vectorization485pub struct Query<'world, 'state, D: QueryData, F: QueryFilter = ()> {486// SAFETY: Must have access to the components registered in `state`.487world: UnsafeWorldCell<'world>,488state: &'state QueryState<D, F>,489last_run: Tick,490this_run: Tick,491}492493impl<D: ReadOnlyQueryData, F: QueryFilter> Clone for Query<'_, '_, D, F> {494fn clone(&self) -> Self {495*self496}497}498499impl<D: ReadOnlyQueryData, F: QueryFilter> Copy for Query<'_, '_, D, F> {}500501impl<D: QueryData, F: QueryFilter> core::fmt::Debug for Query<'_, '_, D, F> {502fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {503f.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}512513impl<'w, 's, D: QueryData, F: QueryFilter> Query<'w, 's, D, F> {514/// Creates a new query.515///516/// # Safety517///518/// * This will create a query that could violate memory safety rules. Make sure that this is only519/// called in ways that ensure the queries have unique mutable access.520/// * `world` must be the world used to create `state`.521#[inline]522pub(crate) unsafe fn new(523world: UnsafeWorldCell<'w>,524state: &'s QueryState<D, F>,525last_run: Tick,526this_run: Tick,527) -> Self {528Self {529world,530state,531last_run,532this_run,533}534}535536/// 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 also543///544/// [`into_readonly`](Self::into_readonly) for a version that consumes the `Query` to return one with the full `'world` lifetime.545pub 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.548unsafe { self.reborrow_unsafe() }.into_readonly()549}550551/// 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`.555fn as_nop(&self) -> Query<'_, 's, NopWorldQuery<D>, F> {556let 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.563unsafe { Query::new(self.world, new_state, self.last_run, self.this_run) }564}565566/// 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 also573///574/// [`as_readonly`](Self::as_readonly) for a version that borrows the `Query` instead of consuming it.575pub fn into_readonly(self) -> Query<'w, 's, D::ReadOnly, F> {576let 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.580unsafe { Query::new(self.world, new_state, self.last_run, self.this_run) }581}582583/// Returns a new `Query` reborrowing the access from this one. The current query will be unusable584/// while the new one exists.585///586/// # Example587///588/// For example this allows to call other methods or other systems that require an owned `Query` without589/// 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/// ```607pub fn reborrow(&mut self) -> Query<'_, 's, D, F> {608// SAFETY: this query is exclusively borrowed while the new one exists, so609// no overlapping access can occur.610unsafe { self.reborrow_unsafe() }611}612613/// 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/// # Safety617///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 also622///623/// - [`reborrow`](Self::reborrow) for the safe versions.624pub 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.628unsafe { self.copy_unsafe() }629}630631/// 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/// # Safety635///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 also640///641/// - [`reborrow_unsafe`](Self::reborrow_unsafe) for a safer version that constrains the returned `'w` lifetime to the length of the borrow.642unsafe 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.646unsafe { Query::new(self.world, self.state, self.last_run, self.this_run) }647}648649/// 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/// # Example655///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 also673///674/// [`iter_mut`](Self::iter_mut) for mutable query items.675#[inline]676pub fn iter(&self) -> QueryIter<'_, 's, D::ReadOnly, F> {677self.as_readonly().into_iter()678}679680/// 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/// # Example686///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 also704///705/// [`iter`](Self::iter) for read-only query items.706#[inline]707pub fn iter_mut(&mut self) -> QueryIter<'_, 's, D, F> {708self.reborrow().into_iter()709}710711/// 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/// # Example717///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 also731///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]735pub fn iter_combinations<const K: usize>(736&self,737) -> QueryCombinationIter<'_, 's, D::ReadOnly, F, K> {738self.as_readonly().iter_combinations_inner()739}740741/// 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/// # Example747///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 data756/// }757/// }758/// ```759///760/// # See also761///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]765pub fn iter_combinations_mut<const K: usize>(766&mut self,767) -> QueryCombinationIter<'_, 's, D, F, K> {768self.reborrow().iter_combinations_inner()769}770771/// 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/// # Example778///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 data787/// }788/// }789/// ```790///791/// # See also792///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]796pub 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.798unsafe { QueryCombinationIter::new(self.world, self.state, self.last_run, self.this_run) }799}800801/// 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 input804/// doesn't guarantee uniqueness. Entities that don't match the query are skipped.805///806/// # Example807///808/// ```809/// # use bevy_ecs::prelude::*;810/// # #[derive(Component)]811/// # struct Counter {812/// # value: i32813/// # }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 also835///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]839pub fn iter_many<EntityList: IntoIterator<Item: EntityEquivalent>>(840&self,841entities: EntityList,842) -> QueryManyIter<'_, 's, D::ReadOnly, F, EntityList::IntoIter> {843self.as_readonly().iter_many_inner(entities)844}845846/// 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 input849/// doesn't guarantee uniqueness. Entities that don't match the query are skipped.850///851/// # Examples852///853/// ```854/// # use bevy_ecs::prelude::*;855/// #[derive(Component)]856/// struct Counter {857/// value: i32858/// }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 also880///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]884pub fn iter_many_mut<EntityList: IntoIterator<Item: EntityEquivalent>>(885&mut self,886entities: EntityList,887) -> QueryManyIter<'_, 's, D, F, EntityList::IntoIter> {888self.reborrow().iter_many_inner(entities)889}890891/// 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 input895/// doesn't guarantee uniqueness. Entities that don't match the query are skipped.896///897/// # See also898///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]902pub fn iter_many_inner<EntityList: IntoIterator<Item: EntityEquivalent>>(903self,904entities: EntityList,905) -> QueryManyIter<'w, 's, D, F, EntityList::IntoIter> {906// SAFETY: `self.world` has permission to access the required components.907unsafe {908QueryManyIter::new(909self.world,910self.state,911entities,912self.last_run,913self.this_run,914)915}916}917918/// 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/// # Example923///924/// ```925/// # use bevy_ecs::{prelude::*, entity::{EntitySet, UniqueEntityIter}};926/// # use core::slice;927/// # #[derive(Component)]928/// # struct Counter {929/// # value: i32930/// # }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 also963///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]967pub fn iter_many_unique<EntityList: EntitySet>(968&self,969entities: EntityList,970) -> QueryManyUniqueIter<'_, 's, D::ReadOnly, F, EntityList::IntoIter> {971self.as_readonly().iter_many_unique_inner(entities)972}973974/// 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/// # Examples979///980/// ```981/// # use bevy_ecs::{prelude::*, entity::{EntitySet, UniqueEntityIter}};982/// # use core::slice;983/// #[derive(Component)]984/// struct Counter {985/// value: i32986/// }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 also1018///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]1022pub fn iter_many_unique_mut<EntityList: EntitySet>(1023&mut self,1024entities: EntityList,1025) -> QueryManyUniqueIter<'_, 's, D, F, EntityList::IntoIter> {1026self.reborrow().iter_many_unique_inner(entities)1027}10281029/// 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/// # Examples1035///1036/// ```1037/// # use bevy_ecs::{prelude::*, entity::{EntitySet, UniqueEntityIter}};1038/// # use core::slice;1039/// #[derive(Component)]1040/// struct Counter {1041/// value: i321042/// }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 also1073///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]1077pub fn iter_many_unique_inner<EntityList: EntitySet>(1078self,1079entities: EntityList,1080) -> QueryManyUniqueIter<'w, 's, D, F, EntityList::IntoIter> {1081// SAFETY: `self.world` has permission to access the required components.1082unsafe {1083QueryManyUniqueIter::new(1084self.world,1085self.state,1086entities,1087self.last_run,1088self.this_run,1089)1090}1091}10921093/// 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/// # Safety1099///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 also1104///1105/// - [`iter`](Self::iter) and [`iter_mut`](Self::iter_mut) for the safe versions.1106#[inline]1107pub unsafe fn iter_unsafe(&self) -> QueryIter<'_, 's, D, F> {1108// SAFETY: The caller promises that this will not result in multiple mutable references.1109unsafe { self.reborrow_unsafe() }.into_iter()1110}11111112/// 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/// # Safety1118///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 also1123///1124/// - [`iter_combinations`](Self::iter_combinations) and [`iter_combinations_mut`](Self::iter_combinations_mut) for the safe versions.1125#[inline]1126pub 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.1130unsafe { self.reborrow_unsafe() }.iter_combinations_inner()1131}11321133/// 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 input1136/// doesnn't guarantee uniqueness. Entities that don't match the query are skipped.1137///1138/// # Safety1139///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 also1145///1146/// - [`iter_many_mut`](Self::iter_many_mut) to safely access the query items.1147pub unsafe fn iter_many_unsafe<EntityList: IntoIterator<Item: EntityEquivalent>>(1148&self,1149entities: EntityList,1150) -> QueryManyIter<'_, 's, D, F, EntityList::IntoIter> {1151// SAFETY: The caller promises that this will not result in multiple mutable references.1152unsafe { self.reborrow_unsafe() }.iter_many_inner(entities)1153}11541155/// 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/// # Safety1160///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 also1165///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.1169pub unsafe fn iter_many_unique_unsafe<EntityList: EntitySet>(1170&self,1171entities: EntityList,1172) -> QueryManyUniqueIter<'_, 's, D, F, EntityList::IntoIter> {1173// SAFETY: The caller promises that this will not result in multiple mutable references.1174unsafe { self.reborrow_unsafe() }.iter_many_unique_inner(entities)1175}11761177/// 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 and1180/// 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 the1188/// results, see [`par_iter_mut`] for an example.1189///1190/// [`par_iter_mut`]: Self::par_iter_mut1191/// [`World`]: crate::world::World1192#[inline]1193pub fn par_iter(&self) -> QueryParIter<'_, 's, D::ReadOnly, F> {1194self.as_readonly().par_iter_inner()1195}11961197/// 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 and1200/// 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/// # Example1208///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_iter1226/// [`World`]: crate::world::World1227#[inline]1228pub fn par_iter_mut(&mut self) -> QueryParIter<'_, 's, D, F> {1229self.reborrow().par_iter_inner()1230}12311232/// 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 and1236/// 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/// # Example1242///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]1259pub fn par_iter_inner(self) -> QueryParIter<'w, 's, D, F> {1260QueryParIter {1261world: self.world,1262state: self.state,1263last_run: self.last_run,1264this_run: self.this_run,1265batching_strategy: BatchingStrategy::new(),1266}1267}12681269/// 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 the1280/// results, see [`par_iter_mut`] for an example.1281///1282/// [`par_iter_many_unique_mut`]: Self::par_iter_many_unique_mut1283/// [`par_iter_mut`]: Self::par_iter_mut1284#[inline]1285pub fn par_iter_many<EntityList: IntoIterator<Item: EntityEquivalent>>(1286&self,1287entities: EntityList,1288) -> QueryParManyIter<'_, 's, D::ReadOnly, F, EntityList::Item> {1289QueryParManyIter {1290world: self.world,1291state: self.state.as_readonly(),1292entity_list: entities.into_iter().collect(),1293last_run: self.last_run,1294this_run: self.this_run,1295batching_strategy: BatchingStrategy::new(),1296}1297}12981299/// 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 the1309/// results, see [`par_iter_mut`] for an example.1310///1311/// [`par_iter_many_unique_mut`]: Self::par_iter_many_unique_mut1312/// [`par_iter_mut`]: Self::par_iter_mut1313#[inline]1314pub fn par_iter_many_unique<EntityList: EntitySet<Item: Sync>>(1315&self,1316entities: EntityList,1317) -> QueryParManyUniqueIter<'_, 's, D::ReadOnly, F, EntityList::Item> {1318QueryParManyUniqueIter {1319world: self.world,1320state: self.state.as_readonly(),1321entity_list: entities.into_iter().collect(),1322last_run: self.last_run,1323this_run: self.this_run,1324batching_strategy: BatchingStrategy::new(),1325}1326}13271328/// 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 the1338/// results, see [`par_iter_mut`] for an example.1339///1340/// [`par_iter_many_unique`]: Self::par_iter_many_unique1341/// [`par_iter_mut`]: Self::par_iter_mut1342#[inline]1343pub fn par_iter_many_unique_mut<EntityList: EntitySet<Item: Sync>>(1344&mut self,1345entities: EntityList,1346) -> QueryParManyUniqueIter<'_, 's, D, F, EntityList::Item> {1347QueryParManyUniqueIter {1348world: self.world,1349state: self.state,1350entity_list: entities.into_iter().collect(),1351last_run: self.last_run,1352this_run: self.this_run,1353batching_strategy: BatchingStrategy::new(),1354}1355}13561357/// Returns a contiguous iterator over the query results for the given1358/// [`World`](crate::world::World) or [`None`] if the query is not dense hence not contiguously1359/// iterable.1360///1361/// Contiguous iteration enables getting slices of contiguously lying components (which lie in the same table), which for example1362/// may be used for simd-operations, which may accelerate an algorithm.1363///1364/// # Example1365///1366/// The following system despawns all entities which health is negative.1367///1368/// ```1369/// # use bevy_ecs::prelude::*;1370/// #1371/// # #[derive(Component)]1372/// # struct Health(pub f32);1373///1374/// fn despawn_all_dead_entities(mut commands: Commands, query: Query<(Entity, &Health)>) {1375/// for (entities, health) in query.contiguous_iter().unwrap() {1376/// // For each entity there is one component, hence it always holds true1377/// assert!(entities.len() == health.len());1378/// for (entity, health) in entities.iter().zip(health.iter()) {1379/// if health.0 < 0.0 {1380/// commands.entity(*entity).despawn();1381/// }1382/// }1383/// }1384/// }1385///1386/// ```1387///1388/// A mutable version: [`Self::contiguous_iter_mut`]1389pub fn contiguous_iter(&self) -> Option<QueryContiguousIter<'_, 's, D::ReadOnly, F>>1390where1391D::ReadOnly: ContiguousQueryData,1392F: ArchetypeFilter,1393{1394self.as_readonly().contiguous_iter_inner().ok()1395}13961397/// Returns a mutable contiguous iterator over the query results for the given1398/// [`World`](crate::world::World) or [`None`] if the query is not dense hence not contiguously1399/// iterable.1400///1401/// Contiguous iteration enables getting slices of contiguously lying components (which lie in the same table), which for example1402/// may be used for simd-operations, which may accelerate an algorithm.1403///1404/// # Example1405///1406/// The following system applies a "health decay" effect on all entities, which reduces their1407/// health by some fraction.1408///1409/// ```1410/// # use bevy_ecs::prelude::*;1411/// #1412/// # #[derive(Component)]1413/// # struct Health(pub f32);1414/// #1415/// # #[derive(Component)]1416/// # struct HealthDecay(pub f32);1417///1418/// fn apply_health_decay(mut query: Query<(&mut Health, &HealthDecay)>) {1419/// for (mut health, decay) in query.contiguous_iter_mut().unwrap() {1420/// // all data slices returned by component queries are the same size1421/// assert!(health.len() == decay.len());1422/// // we could have used health.bypass_change_detection() to do less work.1423/// for (health, decay) in health.iter_mut().zip(decay) {1424/// health.0 *= decay.0;1425/// }1426/// }1427/// }1428/// ```1429/// An immutable version: [`Self::contiguous_iter`]1430pub fn contiguous_iter_mut(&mut self) -> Option<QueryContiguousIter<'_, 's, D, F>>1431where1432D: ContiguousQueryData,1433F: ArchetypeFilter,1434{1435self.reborrow().contiguous_iter_inner().ok()1436}14371438/// Returns a contiguous iterator over the query results for the given1439/// [`World`](crate::world::World) or [`Err`] with this [`Query`] if the query is not dense hence not contiguously1440/// iterable.1441/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.1442pub fn contiguous_iter_inner(self) -> Result<QueryContiguousIter<'w, 's, D, F>, Self>1443where1444D: ContiguousQueryData,1445F: ArchetypeFilter,1446{1447// SAFETY:1448// - `self.world` has permission to access the required components1449// - `self.world` was used to initialize `self.state`1450unsafe { QueryContiguousIter::new(self.world, self.state, self.last_run, self.this_run) }1451.ok_or(self)1452}14531454/// Returns the read-only query item for the given [`Entity`].1455///1456/// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.1457///1458/// This is always guaranteed to run in `O(1)` time.1459///1460/// # Example1461///1462/// Here, `get` is used to retrieve the exact query item of the entity specified by the `SelectedCharacter` resource.1463///1464/// ```1465/// # use bevy_ecs::prelude::*;1466/// #1467/// # #[derive(Resource)]1468/// # struct SelectedCharacter { entity: Entity }1469/// # #[derive(Component)]1470/// # struct Character { name: String }1471/// #1472/// fn print_selected_character_name_system(1473/// query: Query<&Character>,1474/// selection: Res<SelectedCharacter>1475/// )1476/// {1477/// if let Ok(selected_character) = query.get(selection.entity) {1478/// println!("{}", selected_character.name);1479/// }1480/// }1481/// # bevy_ecs::system::assert_is_system(print_selected_character_name_system);1482/// ```1483///1484/// # See also1485///1486/// - [`get_mut`](Self::get_mut) to get a mutable query item.1487#[inline]1488pub fn get(&self, entity: Entity) -> Result<ROQueryItem<'_, 's, D>, QueryEntityError> {1489self.as_readonly().get_inner(entity)1490}14911492/// Returns the read-only query items for the given array of [`Entity`].1493///1494/// The returned query items are in the same order as the input.1495/// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.1496/// The elements of the array do not need to be unique, unlike `get_many_mut`.1497///1498/// # Examples1499///1500/// ```1501/// use bevy_ecs::prelude::*;1502/// use bevy_ecs::query::QueryEntityError;1503///1504/// #[derive(Component, PartialEq, Debug)]1505/// struct A(usize);1506///1507/// let mut world = World::new();1508/// let entity_vec: Vec<Entity> = (0..3).map(|i| world.spawn(A(i)).id()).collect();1509/// let entities: [Entity; 3] = entity_vec.try_into().unwrap();1510///1511/// world.spawn(A(73));1512///1513/// let mut query_state = world.query::<&A>();1514/// let query = query_state.query(&world);1515///1516/// let component_values = query.get_many(entities).unwrap();1517///1518/// assert_eq!(component_values, [&A(0), &A(1), &A(2)]);1519///1520/// let wrong_entity = Entity::from_raw_u32(365).unwrap();1521///1522/// assert_eq!(1523/// match query.get_many([wrong_entity]).unwrap_err() {1524/// QueryEntityError::NotSpawned(error) => error.entity(),1525/// _ => panic!(),1526/// },1527/// wrong_entity1528/// );1529/// ```1530///1531/// # See also1532///1533/// - [`get_many_mut`](Self::get_many_mut) to get mutable query items.1534/// - [`get_many_unique`](Self::get_many_unique) to only handle unique inputs.1535#[inline]1536pub fn get_many<const N: usize>(1537&self,1538entities: [Entity; N],1539) -> Result<[ROQueryItem<'_, 's, D>; N], QueryEntityError> {1540// Note that we call a separate `*_inner` method from `get_many_mut`1541// because we don't need to check for duplicates.1542self.as_readonly().get_many_inner(entities)1543}15441545/// Returns the read-only query items for the given [`UniqueEntityArray`].1546///1547/// The returned query items are in the same order as the input.1548/// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.1549///1550/// # Examples1551///1552/// ```1553/// use bevy_ecs::{prelude::*, query::QueryEntityError, entity::{EntitySetIterator, UniqueEntityArray, UniqueEntityVec}};1554///1555/// #[derive(Component, PartialEq, Debug)]1556/// struct A(usize);1557///1558/// let mut world = World::new();1559/// let entity_set: UniqueEntityVec = world.spawn_batch((0..3).map(A)).collect_set();1560/// let entity_set: UniqueEntityArray<3> = entity_set.try_into().unwrap();1561///1562/// world.spawn(A(73));1563///1564/// let mut query_state = world.query::<&A>();1565/// let query = query_state.query(&world);1566///1567/// let component_values = query.get_many_unique(entity_set).unwrap();1568///1569/// assert_eq!(component_values, [&A(0), &A(1), &A(2)]);1570///1571/// let wrong_entity = Entity::from_raw_u32(365).unwrap();1572///1573/// assert_eq!(1574/// match query.get_many_unique(UniqueEntityArray::from([wrong_entity])).unwrap_err() {1575/// QueryEntityError::NotSpawned(error) => error.entity(),1576/// _ => panic!(),1577/// },1578/// wrong_entity1579/// );1580/// ```1581///1582/// # See also1583///1584/// - [`get_many_unique_mut`](Self::get_many_mut) to get mutable query items.1585/// - [`get_many`](Self::get_many) to handle inputs with duplicates.1586#[inline]1587pub fn get_many_unique<const N: usize>(1588&self,1589entities: UniqueEntityArray<N>,1590) -> Result<[ROQueryItem<'_, 's, D>; N], QueryEntityError> {1591self.as_readonly().get_many_unique_inner(entities)1592}15931594/// Returns the query item for the given [`Entity`].1595///1596/// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.1597///1598/// This is always guaranteed to run in `O(1)` time.1599///1600/// # Example1601///1602/// Here, `get_mut` is used to retrieve the exact query item of the entity specified by the `PoisonedCharacter` resource.1603///1604/// ```1605/// # use bevy_ecs::prelude::*;1606/// #1607/// # #[derive(Resource)]1608/// # struct PoisonedCharacter { character_id: Entity }1609/// # #[derive(Component)]1610/// # struct Health(u32);1611/// #1612/// fn poison_system(mut query: Query<&mut Health>, poisoned: Res<PoisonedCharacter>) {1613/// if let Ok(mut health) = query.get_mut(poisoned.character_id) {1614/// health.0 -= 1;1615/// }1616/// }1617/// # bevy_ecs::system::assert_is_system(poison_system);1618/// ```1619///1620/// # See also1621///1622/// - [`get`](Self::get) to get a read-only query item.1623#[inline]1624pub fn get_mut(&mut self, entity: Entity) -> Result<D::Item<'_, 's>, QueryEntityError> {1625self.reborrow().get_inner(entity)1626}16271628/// Returns the query item for the given [`Entity`].1629/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.1630///1631/// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.1632///1633/// This is always guaranteed to run in `O(1)` time.1634///1635/// # See also1636///1637/// - [`get_mut`](Self::get_mut) to get the item using a mutable borrow of the [`Query`].1638#[inline]1639pub fn get_inner(self, entity: Entity) -> Result<D::Item<'w, 's>, QueryEntityError> {1640// SAFETY: system runs without conflicts with other systems.1641// same-system queries have runtime borrow checks when they conflict1642unsafe {1643let location = self.world.entities().get_spawned(entity)?;1644if !self1645.state1646.matched_archetypes1647.contains(location.archetype_id.index())1648{1649return Err(QueryEntityError::QueryDoesNotMatch(1650entity,1651location.archetype_id,1652));1653}1654let archetype = self1655.world1656.archetypes()1657.get(location.archetype_id)1658.debug_checked_unwrap();1659let mut fetch = D::init_fetch(1660self.world,1661&self.state.fetch_state,1662self.last_run,1663self.this_run,1664);1665let mut filter = F::init_fetch(1666self.world,1667&self.state.filter_state,1668self.last_run,1669self.this_run,1670);16711672let table = self1673.world1674.storages()1675.tables1676.get(location.table_id)1677.debug_checked_unwrap();1678D::set_archetype(&mut fetch, &self.state.fetch_state, archetype, table);1679F::set_archetype(&mut filter, &self.state.filter_state, archetype, table);16801681if F::filter_fetch(1682&self.state.filter_state,1683&mut filter,1684entity,1685location.table_row,1686) && let Some(item) = D::fetch(1687&self.state.fetch_state,1688&mut fetch,1689entity,1690location.table_row,1691) {1692Ok(item)1693} else {1694Err(QueryEntityError::QueryDoesNotMatch(1695entity,1696location.archetype_id,1697))1698}1699}1700}17011702/// Returns the query items for the given array of [`Entity`].1703///1704/// The returned query items are in the same order as the input.1705/// In case of a nonexisting entity, duplicate entities or mismatched component, a [`QueryEntityError`] is returned instead.1706///1707/// # Examples1708///1709/// ```1710/// use bevy_ecs::prelude::*;1711/// use bevy_ecs::query::QueryEntityError;1712///1713/// #[derive(Component, PartialEq, Debug)]1714/// struct A(usize);1715///1716/// let mut world = World::new();1717///1718/// let entities: Vec<Entity> = (0..3).map(|i| world.spawn(A(i)).id()).collect();1719/// let entities: [Entity; 3] = entities.try_into().unwrap();1720///1721/// world.spawn(A(73));1722/// let wrong_entity = Entity::from_raw_u32(57).unwrap();1723/// let invalid_entity = world.spawn_empty().id();1724///1725///1726/// let mut query_state = world.query::<&mut A>();1727/// let mut query = query_state.query_mut(&mut world);1728///1729/// let mut mutable_component_values = query.get_many_mut(entities).unwrap();1730///1731/// for mut a in &mut mutable_component_values {1732/// a.0 += 5;1733/// }1734///1735/// let component_values = query.get_many(entities).unwrap();1736///1737/// assert_eq!(component_values, [&A(5), &A(6), &A(7)]);1738///1739/// assert_eq!(1740/// match query1741/// .get_many_mut([wrong_entity])1742/// .unwrap_err()1743/// {1744/// QueryEntityError::NotSpawned(error) => error.entity(),1745/// _ => panic!(),1746/// },1747/// wrong_entity1748/// );1749/// assert_eq!(1750/// match query1751/// .get_many_mut([invalid_entity])1752/// .unwrap_err()1753/// {1754/// QueryEntityError::QueryDoesNotMatch(entity, _) => entity,1755/// _ => panic!(),1756/// },1757/// invalid_entity1758/// );1759/// assert_eq!(1760/// query1761/// .get_many_mut([entities[0], entities[0]])1762/// .unwrap_err(),1763/// QueryEntityError::AliasedMutability(entities[0])1764/// );1765/// ```1766/// # See also1767///1768/// - [`get_many`](Self::get_many) to get read-only query items without checking for duplicate entities.1769#[inline]1770pub fn get_many_mut<const N: usize>(1771&mut self,1772entities: [Entity; N],1773) -> Result<[D::Item<'_, 's>; N], QueryEntityError> {1774self.reborrow().get_many_mut_inner(entities)1775}17761777/// Returns the query items for the given [`UniqueEntityArray`].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/// # Examples1783///1784/// ```1785/// use bevy_ecs::{prelude::*, query::QueryEntityError, entity::{EntitySetIterator, UniqueEntityArray, UniqueEntityVec}};1786///1787/// #[derive(Component, PartialEq, Debug)]1788/// struct A(usize);1789///1790/// let mut world = World::new();1791///1792/// let entity_set: UniqueEntityVec = world.spawn_batch((0..3).map(A)).collect_set();1793/// let entity_set: UniqueEntityArray<3> = entity_set.try_into().unwrap();1794///1795/// world.spawn(A(73));1796/// let wrong_entity = Entity::from_raw_u32(57).unwrap();1797/// let invalid_entity = world.spawn_empty().id();1798///1799///1800/// let mut query_state = world.query::<&mut A>();1801/// let mut query = query_state.query_mut(&mut world);1802///1803/// let mut mutable_component_values = query.get_many_unique_mut(entity_set).unwrap();1804///1805/// for mut a in &mut mutable_component_values {1806/// a.0 += 5;1807/// }1808///1809/// let component_values = query.get_many_unique(entity_set).unwrap();1810///1811/// assert_eq!(component_values, [&A(5), &A(6), &A(7)]);1812///1813/// assert_eq!(1814/// match query1815/// .get_many_unique_mut(UniqueEntityArray::from([wrong_entity]))1816/// .unwrap_err()1817/// {1818/// QueryEntityError::NotSpawned(error) => error.entity(),1819/// _ => panic!(),1820/// },1821/// wrong_entity1822/// );1823/// assert_eq!(1824/// match query1825/// .get_many_unique_mut(UniqueEntityArray::from([invalid_entity]))1826/// .unwrap_err()1827/// {1828/// QueryEntityError::QueryDoesNotMatch(entity, _) => entity,1829/// _ => panic!(),1830/// },1831/// invalid_entity1832/// );1833/// ```1834/// # See also1835///1836/// - [`get_many_unique`](Self::get_many) to get read-only query items.1837#[inline]1838pub fn get_many_unique_mut<const N: usize>(1839&mut self,1840entities: UniqueEntityArray<N>,1841) -> Result<[D::Item<'_, 's>; N], QueryEntityError> {1842self.reborrow().get_many_unique_inner(entities)1843}18441845/// Returns the query items for the given array of [`Entity`].1846/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.1847///1848/// The returned query items are in the same order as the input.1849/// In case of a nonexisting entity, duplicate entities or mismatched component, a [`QueryEntityError`] is returned instead.1850///1851/// # See also1852///1853/// - [`get_many`](Self::get_many) to get read-only query items without checking for duplicate entities.1854/// - [`get_many_mut`](Self::get_many_mut) to get items using a mutable reference.1855/// - [`get_many_inner`](Self::get_many_mut_inner) to get read-only query items with the actual "inner" world lifetime.1856#[inline]1857pub fn get_many_mut_inner<const N: usize>(1858self,1859entities: [Entity; N],1860) -> Result<[D::Item<'w, 's>; N], QueryEntityError> {1861// Verify that all entities are unique1862for i in 0..N {1863for j in 0..i {1864if entities[i] == entities[j] {1865return Err(QueryEntityError::AliasedMutability(entities[i]));1866}1867}1868}1869// SAFETY: All entities are unique, so the results don't alias.1870unsafe { self.get_many_impl(entities) }1871}18721873/// Returns the query items for the given array of [`Entity`].1874/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.1875///1876/// The returned query items are in the same order as the input.1877/// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.1878///1879/// # See also1880///1881/// - [`get_many`](Self::get_many) to get read-only query items without checking for duplicate entities.1882/// - [`get_many_mut`](Self::get_many_mut) to get items using a mutable reference.1883/// - [`get_many_mut_inner`](Self::get_many_mut_inner) to get mutable query items with the actual "inner" world lifetime.1884#[inline]1885pub fn get_many_inner<const N: usize>(1886self,1887entities: [Entity; N],1888) -> Result<[D::Item<'w, 's>; N], QueryEntityError>1889where1890D: ReadOnlyQueryData,1891{1892// SAFETY: The query results are read-only, so they don't conflict if there are duplicate entities.1893unsafe { self.get_many_impl(entities) }1894}18951896/// Returns the query items for the given [`UniqueEntityArray`].1897/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.1898///1899/// The returned query items are in the same order as the input.1900/// In case of a nonexisting entity, duplicate entities or mismatched component, a [`QueryEntityError`] is returned instead.1901///1902/// # See also1903///1904/// - [`get_many_unique`](Self::get_many_unique) to get read-only query items without checking for duplicate entities.1905/// - [`get_many_unique_mut`](Self::get_many_unique_mut) to get items using a mutable reference.1906#[inline]1907pub fn get_many_unique_inner<const N: usize>(1908self,1909entities: UniqueEntityArray<N>,1910) -> Result<[D::Item<'w, 's>; N], QueryEntityError> {1911// SAFETY: All entities are unique, so the results don't alias.1912unsafe { self.get_many_impl(entities.into_inner()) }1913}19141915/// Returns the query items for the given array of [`Entity`].1916/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.1917///1918/// # Safety1919///1920/// The caller must ensure that the query data returned for the entities does not conflict,1921/// either because they are all unique or because the data is read-only.1922unsafe fn get_many_impl<const N: usize>(1923self,1924entities: [Entity; N],1925) -> Result<[D::Item<'w, 's>; N], QueryEntityError> {1926let mut values = [(); N].map(|_| MaybeUninit::uninit());19271928for (value, entity) in core::iter::zip(&mut values, entities) {1929// SAFETY: The caller asserts that the results don't alias1930let item = unsafe { self.copy_unsafe() }.get_inner(entity)?;1931*value = MaybeUninit::new(item);1932}19331934// SAFETY: Each value has been fully initialized.1935Ok(values.map(|x| unsafe { x.assume_init() }))1936}19371938/// Returns the query item for the given [`Entity`].1939///1940/// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.1941///1942/// This is always guaranteed to run in `O(1)` time.1943///1944/// # Safety1945///1946/// This function makes it possible to violate Rust's aliasing guarantees.1947/// You must make sure this call does not result in multiple mutable references to the same component.1948///1949/// # See also1950///1951/// - [`get_mut`](Self::get_mut) for the safe version.1952#[inline]1953pub unsafe fn get_unchecked(1954&self,1955entity: Entity,1956) -> Result<D::Item<'_, 's>, QueryEntityError> {1957// SAFETY: The caller promises that this will not result in multiple mutable references.1958unsafe { self.reborrow_unsafe() }.get_inner(entity)1959}19601961/// Returns a single read-only query item when there is exactly one entity matching the query.1962///1963/// If the number of query items is not exactly one, a [`QuerySingleError`] is returned instead.1964///1965/// # Example1966///1967/// ```1968/// # use bevy_ecs::prelude::*;1969/// # use bevy_ecs::query::QuerySingleError;1970/// # #[derive(Component)]1971/// # struct PlayerScore(i32);1972/// fn player_scoring_system(query: Query<&PlayerScore>) {1973/// match query.single() {1974/// Ok(PlayerScore(score)) => {1975/// println!("Score: {}", score);1976/// }1977/// Err(QuerySingleError::NoEntities(_)) => {1978/// println!("Error: There is no player!");1979/// }1980/// Err(QuerySingleError::MultipleEntities(_)) => {1981/// println!("Error: There is more than one player!");1982/// }1983/// }1984/// }1985/// # bevy_ecs::system::assert_is_system(player_scoring_system);1986/// ```1987///1988/// # See also1989///1990/// - [`single_mut`](Self::single_mut) to get the mutable query item.1991#[inline]1992pub fn single(&self) -> Result<ROQueryItem<'_, 's, D>, QuerySingleError> {1993self.as_readonly().single_inner()1994}19951996/// Returns a single query item when there is exactly one entity matching the query.1997///1998/// If the number of query items is not exactly one, a [`QuerySingleError`] is returned instead.1999///2000/// # Example2001///2002/// ```2003/// # use bevy_ecs::prelude::*;2004/// #2005/// # #[derive(Component)]2006/// # struct Player;2007/// # #[derive(Component)]2008/// # struct Health(u32);2009/// #2010/// fn regenerate_player_health_system(mut query: Query<&mut Health, With<Player>>) {2011/// let mut health = query.single_mut().expect("Error: Could not find a single player.");2012/// health.0 += 1;2013/// }2014/// # bevy_ecs::system::assert_is_system(regenerate_player_health_system);2015/// ```2016///2017/// # See also2018///2019/// - [`single`](Self::single) to get the read-only query item.2020#[inline]2021pub fn single_mut(&mut self) -> Result<D::Item<'_, 's>, QuerySingleError> {2022self.reborrow().single_inner()2023}20242025/// Returns a single query item when there is exactly one entity matching the query.2026/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.2027///2028/// If the number of query items is not exactly one, a [`QuerySingleError`] is returned instead.2029///2030/// # Example2031///2032/// ```2033/// # use bevy_ecs::prelude::*;2034/// #2035/// # #[derive(Component)]2036/// # struct Player;2037/// # #[derive(Component)]2038/// # struct Health(u32);2039/// #2040/// fn regenerate_player_health_system(query: Query<&mut Health, With<Player>>) {2041/// let mut health = query.single_inner().expect("Error: Could not find a single player.");2042/// health.0 += 1;2043/// }2044/// # bevy_ecs::system::assert_is_system(regenerate_player_health_system);2045/// ```2046///2047/// # See also2048///2049/// - [`single`](Self::single) to get the read-only query item.2050/// - [`single_mut`](Self::single_mut) to get the mutable query item.2051#[inline]2052pub fn single_inner(self) -> Result<D::Item<'w, 's>, QuerySingleError> {2053let mut query = self.into_iter();2054let first = query.next();2055let extra = query.next().is_some();20562057match (first, extra) {2058(Some(r), false) => Ok(r),2059(None, _) => Err(QuerySingleError::NoEntities(DebugName::type_name::<Self>())),2060(Some(_), _) => Err(QuerySingleError::MultipleEntities(DebugName::type_name::<2061Self,2062>())),2063}2064}20652066/// Returns `true` if there are no query items.2067///2068/// This is equivalent to `self.iter().next().is_none()`, and thus the worst case runtime will be `O(n)`2069/// where `n` is the number of *potential* matches. This can be notably expensive for queries that rely2070/// on non-archetypal filters such as [`Added`], [`Changed`] or [`Spawned`] which must individually check2071/// each query result for a match.2072///2073/// # Example2074///2075/// Here, the score is increased only if an entity with a `Player` component is present in the world:2076///2077/// ```2078/// # use bevy_ecs::prelude::*;2079/// #2080/// # #[derive(Component)]2081/// # struct Player;2082/// # #[derive(Resource)]2083/// # struct Score(u32);2084/// fn update_score_system(query: Query<(), With<Player>>, mut score: ResMut<Score>) {2085/// if !query.is_empty() {2086/// score.0 += 1;2087/// }2088/// }2089/// # bevy_ecs::system::assert_is_system(update_score_system);2090/// ```2091///2092/// [`Added`]: crate::query::Added2093/// [`Changed`]: crate::query::Changed2094/// [`Spawned`]: crate::query::Spawned2095#[inline]2096pub fn is_empty(&self) -> bool {2097// If the query data matches every entity, then `as_nop()` can safely2098// skip the cost of initializing the fetch for data that won't be used.2099if D::IS_ARCHETYPAL {2100self.as_nop().iter().next().is_none()2101} else {2102self.iter().next().is_none()2103}2104}21052106/// Returns `true` if the given [`Entity`] matches the query.2107///2108/// This is always guaranteed to run in `O(1)` time.2109///2110/// # Example2111///2112/// ```2113/// # use bevy_ecs::prelude::*;2114/// #2115/// # #[derive(Component)]2116/// # struct InRange;2117/// #2118/// # #[derive(Resource)]2119/// # struct Target {2120/// # entity: Entity,2121/// # }2122/// #2123/// fn targeting_system(in_range_query: Query<&InRange>, target: Res<Target>) {2124/// if in_range_query.contains(target.entity) {2125/// println!("Bam!")2126/// }2127/// }2128/// # bevy_ecs::system::assert_is_system(targeting_system);2129/// ```2130#[inline]2131pub fn contains(&self, entity: Entity) -> bool {2132// If the query data matches every entity, then `as_nop()` can safely2133// skip the cost of initializing the fetch for data that won't be used.2134if D::IS_ARCHETYPAL {2135self.as_nop().get(entity).is_ok()2136} else {2137self.get(entity).is_ok()2138}2139}21402141/// Counts the number of entities that match the query.2142///2143/// This is equivalent to `self.iter().count()` but may be more efficient in some cases.2144///2145/// If [`D::IS_ARCHETYPAL`](QueryData::IS_ARCHETYPAL) && [`F::IS_ARCHETYPAL`](QueryFilter::IS_ARCHETYPAL) is `true`,2146/// this will do work proportional to the number of matched archetypes or tables, but will not iterate each entity.2147/// If it is `false`, it will have to do work for each entity.2148///2149/// # Example2150///2151/// ```2152/// # use bevy_ecs::prelude::*;2153/// #2154/// # #[derive(Component)]2155/// # struct InRange;2156/// #2157/// fn targeting_system(in_range_query: Query<&InRange>) {2158/// let count = in_range_query.count();2159/// println!("{count} targets in range!");2160/// }2161/// # bevy_ecs::system::assert_is_system(targeting_system);2162/// ```2163pub fn count(&self) -> usize {2164// If the query data matches every entity, then `as_nop()` can safely2165// skip the cost of initializing the fetch for data that won't be used.2166if !D::IS_ARCHETYPAL {2167self.into_iter().count()2168} else if !F::IS_ARCHETYPAL {2169// If we have non-archetypal filters, we have to check each entity.2170self.as_nop().into_iter().count()2171} else {2172// For archetypal queries, the `size_hint()` is exact,2173// and we can get the count from the archetype and table counts.2174self.as_nop().into_iter().size_hint().02175}2176}21772178/// Returns a [`QueryLens`] that can be used to construct a new [`Query`] giving more2179/// restrictive access to the entities matched by the current query.2180///2181/// A transmute is valid only if `NewD` has a subset of the read, write, and required access2182/// of the current query. A precise description of the access required by each parameter2183/// type is given in the table below, but typical uses are to:2184/// * Remove components, e.g. `Query<(&A, &B)>` to `Query<&A>`.2185/// * Retrieve an existing component with reduced or equal access, e.g. `Query<&mut A>` to `Query<&A>`2186/// or `Query<&T>` to `Query<Ref<T>>`.2187/// * Add parameters with no new access, for example adding an `Entity` parameter.2188///2189/// Note that since filter terms are dropped, non-archetypal filters like2190/// [`Added`], [`Changed`] and [`Spawned`] will not be respected. To maintain or change filter2191/// terms see [`Self::transmute_lens_filtered`].2192///2193/// |`QueryData` parameter type|Access required|2194/// |----|----|2195/// |[`Entity`], [`EntityLocation`], [`SpawnDetails`], [`&Archetype`], [`Has<T>`], [`PhantomData<T>`]|No access|2196/// |[`EntityMut`]|Read and write access to all components, but no required access|2197/// |[`EntityRef`]|Read access to all components, but no required access|2198/// |`&T`, [`Ref<T>`]|Read and required access to `T`|2199/// |`&mut T`, [`Mut<T>`]|Read, write and required access to `T`|2200/// |[`Option<T>`], [`AnyOf<(D, ...)>`]|Read and write access to `T`, but no required access|2201/// |Tuples of query data and<br/>`#[derive(QueryData)]` structs|The union of the access of their subqueries|2202/// |[`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|2203///2204/// `transmute_lens` drops filter terms, but [`Self::transmute_lens_filtered`] supports returning a [`QueryLens`] with a new2205/// filter type - the access required by filter parameters are as follows.2206///2207/// |`QueryFilter` parameter type|Access required|2208/// |----|----|2209/// |[`Added<T>`], [`Changed<T>`]|Read and required access to `T`|2210/// |[`With<T>`], [`Without<T>`]|No access|2211/// |[`Or<(T, ...)>`]|Read access of the subqueries, but no required access|2212/// |Tuples of query filters and `#[derive(QueryFilter)]` structs|The union of the access of their subqueries|2213///2214/// [`Added`]: crate::query::Added2215/// [`Added<T>`]: crate::query::Added2216/// [`AnyOf<(D, ...)>`]: crate::query::AnyOf2217/// [`&Archetype`]: crate::archetype::Archetype2218/// [`Changed`]: crate::query::Changed2219/// [`Changed<T>`]: crate::query::Changed2220/// [`EntityMut`]: crate::world::EntityMut2221/// [`EntityLocation`]: crate::entity::EntityLocation2222/// [`EntityRef`]: crate::world::EntityRef2223/// [`FilteredEntityRef`]: crate::world::FilteredEntityRef2224/// [`FilteredEntityMut`]: crate::world::FilteredEntityMut2225/// [`Has<T>`]: crate::query::Has2226/// [`Mut<T>`]: crate::world::Mut2227/// [`Or<(T, ...)>`]: crate::query::Or2228/// [`QueryBuilder`]: crate::query::QueryBuilder2229/// [`Ref<T>`]: crate::world::Ref2230/// [`SpawnDetails`]: crate::query::SpawnDetails2231/// [`Spawned`]: crate::query::Spawned2232/// [`With<T>`]: crate::query::With2233/// [`Without<T>`]: crate::query::Without2234///2235/// ## Panics2236///2237/// This will panic if the access required by `NewD` is not a subset of that required by2238/// the original fetch `D`.2239///2240/// ## Example2241///2242/// ```rust2243/// # use bevy_ecs::prelude::*;2244/// # use bevy_ecs::system::QueryLens;2245/// #2246/// # #[derive(Component)]2247/// # struct A(usize);2248/// #2249/// # #[derive(Component)]2250/// # struct B(usize);2251/// #2252/// # let mut world = World::new();2253/// #2254/// # world.spawn((A(10), B(5)));2255/// #2256/// fn reusable_function(lens: &mut QueryLens<&A>) {2257/// assert_eq!(lens.query().single().unwrap().0, 10);2258/// }2259///2260/// // We can use the function in a system that takes the exact query.2261/// fn system_1(mut query: Query<&A>) {2262/// reusable_function(&mut query.as_query_lens());2263/// }2264///2265/// // We can also use it with a query that does not match exactly2266/// // by transmuting it.2267/// fn system_2(mut query: Query<(&mut A, &B)>) {2268/// let mut lens = query.transmute_lens::<&A>();2269/// reusable_function(&mut lens);2270/// }2271///2272/// # let mut schedule = Schedule::default();2273/// # schedule.add_systems((system_1, system_2));2274/// # schedule.run(&mut world);2275/// ```2276///2277/// ### Examples of valid transmutes2278///2279/// ```rust2280/// # use bevy_ecs::{2281/// # prelude::*,2282/// # archetype::Archetype,2283/// # entity::EntityLocation,2284/// # query::{QueryData, QueryFilter},2285/// # world::{FilteredEntityMut, FilteredEntityRef},2286/// # };2287/// # use std::marker::PhantomData;2288/// #2289/// # fn assert_valid_transmute<OldD: QueryData, NewD: QueryData>() {2290/// # assert_valid_transmute_filtered::<OldD, (), NewD, ()>();2291/// # }2292/// #2293/// # fn assert_valid_transmute_filtered<OldD: QueryData, OldF: QueryFilter, NewD: QueryData, NewF: QueryFilter>() {2294/// # let mut world = World::new();2295/// # // Make sure all components in the new query are initialized2296/// # let state = world.query_filtered::<NewD, NewF>();2297/// # let state = world.query_filtered::<OldD, OldF>();2298/// # state.transmute_filtered::<NewD, NewF>(&world);2299/// # }2300/// #2301/// # #[derive(Component)]2302/// # struct T;2303/// #2304/// # #[derive(Component)]2305/// # struct U;2306/// #2307/// # #[derive(Component)]2308/// # struct V;2309/// #2310/// // `&mut T` and `Mut<T>` access the same data and can be transmuted to each other,2311/// // `&T` and `Ref<T>` access the same data and can be transmuted to each other,2312/// // and mutable versions can be transmuted to read-only versions2313/// assert_valid_transmute::<&mut T, &T>();2314/// assert_valid_transmute::<&mut T, Mut<T>>();2315/// assert_valid_transmute::<Mut<T>, &mut T>();2316/// assert_valid_transmute::<&T, Ref<T>>();2317/// assert_valid_transmute::<Ref<T>, &T>();2318///2319/// // The structure can be rearranged, or subqueries dropped2320/// assert_valid_transmute::<(&T, &U), &T>();2321/// assert_valid_transmute::<((&T, &U), &V), (&T, (&U, &V))>();2322/// assert_valid_transmute::<Option<(&T, &U)>, (Option<&T>, Option<&U>)>();2323///2324/// // Queries with no access can be freely added2325/// assert_valid_transmute::<2326/// &T,2327/// (&T, Entity, EntityLocation, &Archetype, Has<U>, PhantomData<T>),2328/// >();2329///2330/// // Required access can be transmuted to optional,2331/// // and optional access can be transmuted to other optional access2332/// assert_valid_transmute::<&T, Option<&T>>();2333/// assert_valid_transmute::<AnyOf<(&mut T, &mut U)>, Option<&T>>();2334/// // Note that removing subqueries from `AnyOf` will result2335/// // in an `AnyOf` where all subqueries can yield `None`!2336/// assert_valid_transmute::<AnyOf<(&T, &U, &V)>, AnyOf<(&T, &U)>>();2337/// assert_valid_transmute::<EntityMut, Option<&mut T>>();2338///2339/// // Anything can be transmuted to `FilteredEntityRef` or `FilteredEntityMut`2340/// // This will create a `FilteredEntityMut` that only has read access to `T`2341/// assert_valid_transmute::<&T, FilteredEntityMut>();2342/// // This will create a `FilteredEntityMut` that has no access to `T`,2343/// // read access to `U`, and write access to `V`.2344/// assert_valid_transmute::<(&mut T, &mut U, &mut V), (&mut T, &U, FilteredEntityMut)>();2345///2346/// // `Added<T>` and `Changed<T>` filters have the same access as `&T` data2347/// // Remember that they are only evaluated on the transmuted query, not the original query!2348/// assert_valid_transmute_filtered::<Entity, Changed<T>, &T, ()>();2349/// assert_valid_transmute_filtered::<&mut T, (), &T, Added<T>>();2350/// // Nested inside of an `Or` filter, they have the same access as `Option<&T>`.2351/// assert_valid_transmute_filtered::<Option<&T>, (), Entity, Or<(Changed<T>, With<U>)>>();2352/// ```2353#[track_caller]2354pub fn transmute_lens<NewD: QueryData>(&mut self) -> QueryLens<'_, NewD> {2355self.transmute_lens_filtered::<NewD, ()>()2356}23572358/// Returns a [`QueryLens`] that can be used to construct a new `Query` giving more restrictive2359/// access to the entities matched by the current query.2360///2361/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.2362///2363/// See [`Self::transmute_lens`] for a description of allowed transmutes.2364///2365/// ## Panics2366///2367/// This will panic if `NewD` is not a subset of the original fetch `D`2368///2369/// ## Example2370///2371/// ```rust2372/// # use bevy_ecs::prelude::*;2373/// # use bevy_ecs::system::QueryLens;2374/// #2375/// # #[derive(Component)]2376/// # struct A(usize);2377/// #2378/// # #[derive(Component)]2379/// # struct B(usize);2380/// #2381/// # let mut world = World::new();2382/// #2383/// # world.spawn((A(10), B(5)));2384/// #2385/// fn reusable_function(mut lens: QueryLens<&A>) {2386/// assert_eq!(lens.query().single().unwrap().0, 10);2387/// }2388///2389/// // We can use the function in a system that takes the exact query.2390/// fn system_1(query: Query<&A>) {2391/// reusable_function(query.into_query_lens());2392/// }2393///2394/// // We can also use it with a query that does not match exactly2395/// // by transmuting it.2396/// fn system_2(query: Query<(&mut A, &B)>) {2397/// let mut lens = query.transmute_lens_inner::<&A>();2398/// reusable_function(lens);2399/// }2400///2401/// # let mut schedule = Schedule::default();2402/// # schedule.add_systems((system_1, system_2));2403/// # schedule.run(&mut world);2404/// ```2405///2406/// # See also2407///2408/// - [`transmute_lens`](Self::transmute_lens) to convert to a lens using a mutable borrow of the [`Query`].2409#[track_caller]2410pub fn transmute_lens_inner<NewD: QueryData>(self) -> QueryLens<'w, NewD> {2411self.transmute_lens_filtered_inner::<NewD, ()>()2412}24132414/// Equivalent to [`Self::transmute_lens`] but also includes a [`QueryFilter`] type.2415///2416/// See [`Self::transmute_lens`] for a description of allowed transmutes.2417///2418/// Note that the lens will iterate the same tables and archetypes as the original query. This means that2419/// additional archetypal query terms like [`With`](crate::query::With) and [`Without`](crate::query::Without)2420/// will not necessarily be respected and non-archetypal terms like [`Added`](crate::query::Added),2421/// [`Changed`](crate::query::Changed) and [`Spawned`](crate::query::Spawned) will only be respected if they2422/// are in the type signature.2423#[track_caller]2424pub fn transmute_lens_filtered<NewD: QueryData, NewF: QueryFilter>(2425&mut self,2426) -> QueryLens<'_, NewD, NewF> {2427self.reborrow().transmute_lens_filtered_inner()2428}24292430/// Equivalent to [`Self::transmute_lens_inner`] but also includes a [`QueryFilter`] type.2431/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.2432///2433/// See [`Self::transmute_lens`] for a description of allowed transmutes.2434///2435/// Note that the lens will iterate the same tables and archetypes as the original query. This means that2436/// additional archetypal query terms like [`With`](crate::query::With) and [`Without`](crate::query::Without)2437/// will not necessarily be respected and non-archetypal terms like [`Added`](crate::query::Added),2438/// [`Changed`](crate::query::Changed) and [`Spawned`](crate::query::Spawned) will only be respected if they2439/// are in the type signature.2440///2441/// # See also2442///2443/// - [`transmute_lens_filtered`](Self::transmute_lens_filtered) to convert to a lens using a mutable borrow of the [`Query`].2444#[track_caller]2445pub fn transmute_lens_filtered_inner<NewD: QueryData, NewF: QueryFilter>(2446self,2447) -> QueryLens<'w, NewD, NewF> {2448let state = self.state.transmute_filtered::<NewD, NewF>(self.world);2449QueryLens {2450world: self.world,2451state,2452last_run: self.last_run,2453this_run: self.this_run,2454}2455}24562457/// Gets a [`QueryLens`] with the same accesses as the existing query2458pub fn as_query_lens(&mut self) -> QueryLens<'_, D> {2459self.transmute_lens()2460}24612462/// Gets a [`QueryLens`] with the same accesses as the existing query2463///2464/// # See also2465///2466/// - [`as_query_lens`](Self::as_query_lens) to convert to a lens using a mutable borrow of the [`Query`].2467pub fn into_query_lens(self) -> QueryLens<'w, D> {2468self.transmute_lens_inner()2469}24702471/// Returns a [`QueryLens`] that can be used to get a query with the combined fetch.2472///2473/// For example, this can take a `Query<&A>` and a `Query<&B>` and return a `Query<(&A, &B)>`.2474/// The returned query will only return items with both `A` and `B`. Note that since filters2475/// are dropped, non-archetypal filters like `Added`, `Changed` and `Spawned` will not be respected.2476/// To maintain or change filter terms see `Self::join_filtered`.2477///2478/// ## Example2479///2480/// ```rust2481/// # use bevy_ecs::prelude::*;2482/// # use bevy_ecs::system::QueryLens;2483/// #2484/// # #[derive(Component)]2485/// # struct Transform;2486/// #2487/// # #[derive(Component)]2488/// # struct Player;2489/// #2490/// # #[derive(Component)]2491/// # struct Enemy;2492/// #2493/// # let mut world = World::default();2494/// # world.spawn((Transform, Player));2495/// # world.spawn((Transform, Enemy));2496///2497/// fn system(2498/// mut transforms: Query<&Transform>,2499/// mut players: Query<&Player>,2500/// mut enemies: Query<&Enemy>2501/// ) {2502/// let mut players_transforms: QueryLens<(&Transform, &Player)> = transforms.join(&mut players);2503/// for (transform, player) in &players_transforms.query() {2504/// // do something with a and b2505/// }2506///2507/// let mut enemies_transforms: QueryLens<(&Transform, &Enemy)> = transforms.join(&mut enemies);2508/// for (transform, enemy) in &enemies_transforms.query() {2509/// // do something with a and b2510/// }2511/// }2512///2513/// # let mut schedule = Schedule::default();2514/// # schedule.add_systems(system);2515/// # schedule.run(&mut world);2516/// ```2517/// ## Panics2518///2519/// This will panic if `NewD` is not a subset of the union of the original fetch `Q` and `OtherD`.2520///2521/// ## Allowed Transmutes2522///2523/// Like `transmute_lens` the query terms can be changed with some restrictions.2524/// See [`Self::transmute_lens`] for more details.2525pub fn join<'a, OtherD: QueryData, NewD: QueryData>(2526&'a mut self,2527other: &'a mut Query<OtherD>,2528) -> QueryLens<'a, NewD> {2529self.join_filtered(other)2530}25312532/// Returns a [`QueryLens`] that can be used to get a query with the combined fetch.2533/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.2534///2535/// For example, this can take a `Query<&A>` and a `Query<&B>` and return a `Query<(&A, &B)>`.2536/// The returned query will only return items with both `A` and `B`. Note that since filters2537/// are dropped, non-archetypal filters like `Added`, `Changed` and `Spawned` will not be respected.2538/// To maintain or change filter terms see `Self::join_filtered`.2539///2540/// ## Panics2541///2542/// This will panic if `NewD` is not a subset of the union of the original fetch `Q` and `OtherD`.2543///2544/// ## Allowed Transmutes2545///2546/// Like `transmute_lens` the query terms can be changed with some restrictions.2547/// See [`Self::transmute_lens`] for more details.2548///2549/// # See also2550///2551/// - [`join`](Self::join) to join using a mutable borrow of the [`Query`].2552pub fn join_inner<OtherD: QueryData, NewD: QueryData>(2553self,2554other: Query<'w, '_, OtherD>,2555) -> QueryLens<'w, NewD> {2556self.join_filtered_inner(other)2557}25582559/// Equivalent to [`Self::join`] but also includes a [`QueryFilter`] type.2560///2561/// Note that the lens with iterate a subset of the original queries' tables2562/// and archetypes. This means that additional archetypal query terms like2563/// `With` and `Without` will not necessarily be respected and non-archetypal2564/// terms like `Added`, `Changed` and `Spawned` will only be respected if they2565/// are in the type signature.2566pub fn join_filtered<2567'a,2568OtherD: QueryData,2569OtherF: QueryFilter,2570NewD: QueryData,2571NewF: QueryFilter,2572>(2573&'a mut self,2574other: &'a mut Query<OtherD, OtherF>,2575) -> QueryLens<'a, NewD, NewF> {2576self.reborrow().join_filtered_inner(other.reborrow())2577}25782579/// Equivalent to [`Self::join_inner`] but also includes a [`QueryFilter`] type.2580/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.2581///2582/// Note that the lens with iterate a subset of the original queries' tables2583/// and archetypes. This means that additional archetypal query terms like2584/// `With` and `Without` will not necessarily be respected and non-archetypal2585/// terms like `Added`, `Changed` and `Spawned` will only be respected if they2586/// are in the type signature.2587///2588/// # See also2589///2590/// - [`join_filtered`](Self::join_filtered) to join using a mutable borrow of the [`Query`].2591pub fn join_filtered_inner<2592OtherD: QueryData,2593OtherF: QueryFilter,2594NewD: QueryData,2595NewF: QueryFilter,2596>(2597self,2598other: Query<'w, '_, OtherD, OtherF>,2599) -> QueryLens<'w, NewD, NewF> {2600let state = self2601.state2602.join_filtered::<OtherD, OtherF, NewD, NewF>(self.world, other.state);2603QueryLens {2604world: self.world,2605state,2606last_run: self.last_run,2607this_run: self.this_run,2608}2609}2610}26112612impl<'w, 's, D: QueryData, F: QueryFilter> IntoIterator for Query<'w, 's, D, F> {2613type Item = D::Item<'w, 's>;2614type IntoIter = QueryIter<'w, 's, D, F>;26152616fn into_iter(self) -> Self::IntoIter {2617// SAFETY:2618// - `self.world` has permission to access the required components.2619// - We consume the query, so mutable queries cannot alias.2620// Read-only queries are `Copy`, but may alias themselves.2621unsafe { QueryIter::new(self.world, self.state, self.last_run, self.this_run) }2622}2623}26242625impl<'w, 's, D: QueryData, F: QueryFilter> IntoIterator for &'w Query<'_, 's, D, F> {2626type Item = ROQueryItem<'w, 's, D>;2627type IntoIter = QueryIter<'w, 's, D::ReadOnly, F>;26282629fn into_iter(self) -> Self::IntoIter {2630self.iter()2631}2632}26332634impl<'w, 's, D: QueryData, F: QueryFilter> IntoIterator for &'w mut Query<'_, 's, D, F> {2635type Item = D::Item<'w, 's>;2636type IntoIter = QueryIter<'w, 's, D, F>;26372638fn into_iter(self) -> Self::IntoIter {2639self.iter_mut()2640}2641}26422643impl<'w, 's, D: ReadOnlyQueryData, F: QueryFilter> Query<'w, 's, D, F> {2644/// Returns an [`Iterator`] over the query items, with the actual "inner" world lifetime.2645///2646/// This can only return immutable data (mutable data will be cast to an immutable form).2647/// See [`Self::iter_mut`] for queries that contain at least one mutable component.2648///2649/// # Example2650///2651/// Here, the `report_names_system` iterates over the `Player` component of every entity2652/// that contains it:2653///2654/// ```2655/// # use bevy_ecs::prelude::*;2656/// #2657/// # #[derive(Component)]2658/// # struct Player { name: String }2659/// #2660/// fn report_names_system(query: Query<&Player>) {2661/// for player in &query {2662/// println!("Say hello to {}!", player.name);2663/// }2664/// }2665/// # bevy_ecs::system::assert_is_system(report_names_system);2666/// ```2667#[inline]2668pub fn iter_inner(&self) -> QueryIter<'w, 's, D::ReadOnly, F> {2669(*self).into_iter()2670}2671}26722673/// Type returned from [`Query::transmute_lens`] containing the new [`QueryState`].2674///2675/// Call [`query`](QueryLens::query) or [`into`](Into::into) to construct the resulting [`Query`]2676pub struct QueryLens<'w, Q: QueryData, F: QueryFilter = ()> {2677world: UnsafeWorldCell<'w>,2678state: QueryState<Q, F>,2679last_run: Tick,2680this_run: Tick,2681}26822683impl<'w, Q: QueryData, F: QueryFilter> QueryLens<'w, Q, F> {2684/// Create a [`Query`] from the underlying [`QueryState`].2685pub fn query(&mut self) -> Query<'_, '_, Q, F> {2686Query {2687world: self.world,2688state: &self.state,2689last_run: self.last_run,2690this_run: self.this_run,2691}2692}2693}26942695impl<'w, Q: ReadOnlyQueryData, F: QueryFilter> QueryLens<'w, Q, F> {2696/// Create a [`Query`] from the underlying [`QueryState`].2697/// This returns results with the actual "inner" world lifetime,2698/// so it may only be used with read-only queries to prevent mutable aliasing.2699pub fn query_inner(&self) -> Query<'w, '_, Q, F> {2700Query {2701world: self.world,2702state: &self.state,2703last_run: self.last_run,2704this_run: self.this_run,2705}2706}2707}27082709impl<'w, 's, Q: QueryData, F: QueryFilter> From<&'s mut QueryLens<'w, Q, F>>2710for Query<'s, 's, Q, F>2711{2712fn from(value: &'s mut QueryLens<'w, Q, F>) -> Query<'s, 's, Q, F> {2713value.query()2714}2715}27162717impl<'w, 'q, Q: QueryData, F: QueryFilter> From<&'q mut Query<'w, '_, Q, F>>2718for QueryLens<'q, Q, F>2719{2720fn from(value: &'q mut Query<'w, '_, Q, F>) -> QueryLens<'q, Q, F> {2721value.transmute_lens_filtered()2722}2723}27242725/// [System parameter] that provides access to single entity's components, much like [`Query::single`]/[`Query::single_mut`].2726///2727/// This [`SystemParam`](crate::system::SystemParam) fails validation if zero or more than one matching entity exists.2728/// This will cause the system to be skipped, according to the rules laid out in [`SystemParamValidationError`](crate::system::SystemParamValidationError).2729///2730/// Use [`Option<Single<D, F>>`] instead if zero or one matching entities can exist.2731///2732/// Note that [`Single`] is not used as a search optimization. It is used as a validation with slight overhead compared to [`Query`].2733///2734/// See [`Query`] for more details.2735///2736/// [System parameter]: crate::system::SystemParam2737///2738/// # Example2739/// ```2740/// # use bevy_ecs::prelude::*;2741/// #[derive(Component)]2742/// struct Boss {2743/// health: f322744/// };2745///2746/// fn hurt_boss(mut boss: Single<&mut Boss>) {2747/// boss.health -= 4.0;2748/// }2749/// ```2750/// Note that because [`Single`] implements [`Deref`] and [`DerefMut`], methods and fields like `health` can be accessed directly.2751/// You can also access the underlying data manually, by calling `.deref`/`.deref_mut`, or by using the `*` operator.2752pub struct Single<'w, 's, D: QueryData, F: QueryFilter = ()> {2753pub(crate) item: D::Item<'w, 's>,2754pub(crate) _filter: PhantomData<F>,2755}27562757impl<'w, 's, D: QueryData, F: QueryFilter> Deref for Single<'w, 's, D, F> {2758type Target = D::Item<'w, 's>;27592760fn deref(&self) -> &Self::Target {2761&self.item2762}2763}27642765impl<'w, 's, D: QueryData, F: QueryFilter> DerefMut for Single<'w, 's, D, F> {2766fn deref_mut(&mut self) -> &mut Self::Target {2767&mut self.item2768}2769}27702771impl<'w, 's, D: QueryData, F: QueryFilter> Single<'w, 's, D, F> {2772/// Returns the inner item with ownership.2773pub fn into_inner(self) -> D::Item<'w, 's> {2774self.item2775}2776}27772778/// [System parameter] that works very much like [`Query`] except it always contains at least one matching entity.2779///2780/// This [`SystemParam`](crate::system::SystemParam) fails validation if no matching entities exist.2781/// This will cause the system to be skipped, according to the rules laid out in [`SystemParamValidationError`](crate::system::SystemParamValidationError).2782///2783/// Much like [`Query::is_empty`] the worst case runtime will be `O(n)` where `n` is the number of *potential* matches.2784/// This can be notably expensive for queries that rely on non-archetypal filters such as [`Added`](crate::query::Added),2785/// [`Changed`](crate::query::Changed) of [`Spawned`](crate::query::Spawned) which must individually check each query2786/// result for a match.2787///2788/// See [`Query`] for more details.2789///2790/// [System parameter]: crate::system::SystemParam2791pub struct Populated<'w, 's, D: QueryData, F: QueryFilter = ()>(pub(crate) Query<'w, 's, D, F>);27922793impl<'w, 's, D: QueryData, F: QueryFilter> Deref for Populated<'w, 's, D, F> {2794type Target = Query<'w, 's, D, F>;27952796fn deref(&self) -> &Self::Target {2797&self.02798}2799}28002801impl<D: QueryData, F: QueryFilter> DerefMut for Populated<'_, '_, D, F> {2802fn deref_mut(&mut self) -> &mut Self::Target {2803&mut self.02804}2805}28062807impl<'w, 's, D: QueryData, F: QueryFilter> Populated<'w, 's, D, F> {2808/// Returns the inner item with ownership.2809pub fn into_inner(self) -> Query<'w, 's, D, F> {2810self.02811}2812}28132814impl<'w, 's, D: QueryData, F: QueryFilter> IntoIterator for Populated<'w, 's, D, F> {2815type Item = <Query<'w, 's, D, F> as IntoIterator>::Item;28162817type IntoIter = <Query<'w, 's, D, F> as IntoIterator>::IntoIter;28182819fn into_iter(self) -> Self::IntoIter {2820self.0.into_iter()2821}2822}28232824impl<'a, 'w, 's, D: QueryData, F: QueryFilter> IntoIterator for &'a Populated<'w, 's, D, F> {2825type Item = <&'a Query<'w, 's, D, F> as IntoIterator>::Item;28262827type IntoIter = <&'a Query<'w, 's, D, F> as IntoIterator>::IntoIter;28282829fn into_iter(self) -> Self::IntoIter {2830self.deref().into_iter()2831}2832}28332834impl<'a, 'w, 's, D: QueryData, F: QueryFilter> IntoIterator for &'a mut Populated<'w, 's, D, F> {2835type Item = <&'a mut Query<'w, 's, D, F> as IntoIterator>::Item;28362837type IntoIter = <&'a mut Query<'w, 's, D, F> as IntoIterator>::IntoIter;28382839fn into_iter(self) -> Self::IntoIter {2840self.deref_mut().into_iter()2841}2842}28432844#[cfg(test)]2845mod tests {2846use crate::{prelude::*, query::QueryEntityError};2847use alloc::vec::Vec;28482849#[test]2850fn get_many_uniqueness() {2851let mut world = World::new();28522853let entities: Vec<Entity> = (0..10).map(|_| world.spawn_empty().id()).collect();28542855let mut query_state = world.query::<Entity>();28562857// It's best to test get_many_mut_inner directly, as it is shared2858// We don't care about aliased mutability for the read-only equivalent28592860// SAFETY: Query does not access world data.2861assert!(query_state2862.query_mut(&mut world)2863.get_many_mut_inner::<10>(entities.clone().try_into().unwrap())2864.is_ok());28652866assert_eq!(2867query_state2868.query_mut(&mut world)2869.get_many_mut_inner([entities[0], entities[0]])2870.unwrap_err(),2871QueryEntityError::AliasedMutability(entities[0])2872);28732874assert_eq!(2875query_state2876.query_mut(&mut world)2877.get_many_mut_inner([entities[0], entities[1], entities[0]])2878.unwrap_err(),2879QueryEntityError::AliasedMutability(entities[0])2880);28812882assert_eq!(2883query_state2884.query_mut(&mut world)2885.get_many_mut_inner([entities[9], entities[9]])2886.unwrap_err(),2887QueryEntityError::AliasedMutability(entities[9])2888);2889}2890}289128922893