use bevy_utils::prelude::DebugName;12use crate::{3batching::BatchingStrategy,4component::Tick,5entity::{Entity, EntityDoesNotExistError, EntityEquivalent, EntitySet, UniqueEntityArray},6query::{7DebugCheckedUnwrap, NopWorldQuery, QueryCombinationIter, QueryData, QueryEntityError,8QueryFilter, QueryIter, QueryManyIter, QueryManyUniqueIter, QueryParIter, QueryParManyIter,9QueryParManyUniqueIter, QuerySingleError, QueryState, ROQueryItem, ReadOnlyQueryData,10},11world::unsafe_world_cell::UnsafeWorldCell,12};13use core::{14marker::PhantomData,15mem::MaybeUninit,16ops::{Deref, DerefMut},17};1819/// A [system parameter] that provides selective access to the [`Component`] data stored in a [`World`].20///21/// Queries enable systems to access [entity identifiers] and [components] without requiring direct access to the [`World`].22/// Its iterators and getter methods return *query items*, which are types containing data related to an entity.23///24/// `Query` is a generic data structure that accepts two type parameters:25///26/// - **`D` (query data)**:27/// The type of data fetched by the query, which will be returned as the query item.28/// Only entities that match the requested data will generate an item.29/// Must implement the [`QueryData`] trait.30/// - **`F` (query filter)**:31/// An optional set of conditions that determine whether query items should be kept or discarded.32/// This defaults to [`unit`], which means no additional filters will be applied.33/// Must implement the [`QueryFilter`] trait.34///35/// [system parameter]: crate::system::SystemParam36/// [`Component`]: crate::component::Component37/// [`World`]: crate::world::World38/// [entity identifiers]: Entity39/// [components]: crate::component::Component40///41/// # Similar parameters42///43/// `Query` has few sibling [`SystemParam`]s, which perform additional validation:44///45/// - [`Single`] - Exactly one matching query item.46/// - [`Option<Single>`] - Zero or one matching query item.47/// - [`Populated`] - At least one matching query item.48///49/// These parameters will prevent systems from running if their requirements are not met.50///51/// [`SystemParam`]: crate::system::system_param::SystemParam52/// [`Option<Single>`]: Single53///54/// # System parameter declaration55///56/// A query should always be declared as a system parameter.57/// This section shows the most common idioms involving the declaration of `Query`.58///59/// ## Component access60///61/// You can fetch an entity's component by specifying a reference to that component in the query's data parameter:62///63/// ```64/// # use bevy_ecs::prelude::*;65/// #66/// # #[derive(Component)]67/// # struct ComponentA;68/// #69/// // A component can be accessed by a shared reference...70/// fn immutable_query(query: Query<&ComponentA>) {71/// // ...72/// }73///74/// // ...or by a mutable reference.75/// fn mutable_query(query: Query<&mut ComponentA>) {76/// // ...77/// }78/// #79/// # bevy_ecs::system::assert_is_system(immutable_query);80/// # bevy_ecs::system::assert_is_system(mutable_query);81/// ```82///83/// Note that components need to be behind a reference (`&` or `&mut`), or the query will not compile:84///85/// ```compile_fail,E027786/// # use bevy_ecs::prelude::*;87/// #88/// # #[derive(Component)]89/// # struct ComponentA;90/// #91/// // This needs to be `&ComponentA` or `&mut ComponentA` in order to compile.92/// fn invalid_query(query: Query<ComponentA>) {93/// // ...94/// }95/// ```96///97/// ## Query filtering98///99/// Setting the query filter type parameter will ensure that each query item satisfies the given condition:100///101/// ```102/// # use bevy_ecs::prelude::*;103/// #104/// # #[derive(Component)]105/// # struct ComponentA;106/// #107/// # #[derive(Component)]108/// # struct ComponentB;109/// #110/// // `ComponentA` data will be accessed, but only for entities that also contain `ComponentB`.111/// fn filtered_query(query: Query<&ComponentA, With<ComponentB>>) {112/// // ...113/// }114/// #115/// # bevy_ecs::system::assert_is_system(filtered_query);116/// ```117///118/// Note that the filter is `With<ComponentB>`, not `With<&ComponentB>`. Unlike query data, `With`119/// does not require components to be behind a reference.120///121/// ## `QueryData` or `QueryFilter` tuples122///123/// Using [`tuple`]s, each `Query` type parameter can contain multiple elements.124///125/// In the following example two components are accessed simultaneously, and the query items are126/// filtered on two conditions:127///128/// ```129/// # use bevy_ecs::prelude::*;130/// #131/// # #[derive(Component)]132/// # struct ComponentA;133/// #134/// # #[derive(Component)]135/// # struct ComponentB;136/// #137/// # #[derive(Component)]138/// # struct ComponentC;139/// #140/// # #[derive(Component)]141/// # struct ComponentD;142/// #143/// fn complex_query(144/// query: Query<(&mut ComponentA, &ComponentB), (With<ComponentC>, Without<ComponentD>)>145/// ) {146/// // ...147/// }148/// #149/// # bevy_ecs::system::assert_is_system(complex_query);150/// ```151///152/// Note that this currently only works on tuples with 15 or fewer items. You may nest tuples to153/// get around this limit:154///155/// ```156/// # use bevy_ecs::prelude::*;157/// #158/// # #[derive(Component)]159/// # struct ComponentA;160/// #161/// # #[derive(Component)]162/// # struct ComponentB;163/// #164/// # #[derive(Component)]165/// # struct ComponentC;166/// #167/// # #[derive(Component)]168/// # struct ComponentD;169/// #170/// fn nested_query(171/// query: Query<(&ComponentA, &ComponentB, (&mut ComponentC, &mut ComponentD))>172/// ) {173/// // ...174/// }175/// #176/// # bevy_ecs::system::assert_is_system(nested_query);177/// ```178///179/// ## Entity identifier access180///181/// You can access [`Entity`], the entity identifier, by including it in the query data parameter:182///183/// ```184/// # use bevy_ecs::prelude::*;185/// #186/// # #[derive(Component)]187/// # struct ComponentA;188/// #189/// fn entity_id_query(query: Query<(Entity, &ComponentA)>) {190/// // ...191/// }192/// #193/// # bevy_ecs::system::assert_is_system(entity_id_query);194/// ```195///196/// Be aware that [`Entity`] is not a component, so it does not need to be behind a reference.197///198/// ## Optional component access199///200/// A component can be made optional by wrapping it into an [`Option`]. In the following example, a201/// query item will still be generated even if the queried entity does not contain `ComponentB`.202/// When this is the case, `Option<&ComponentB>`'s corresponding value will be `None`.203///204/// ```205/// # use bevy_ecs::prelude::*;206/// #207/// # #[derive(Component)]208/// # struct ComponentA;209/// #210/// # #[derive(Component)]211/// # struct ComponentB;212/// #213/// // Queried items must contain `ComponentA`. If they also contain `ComponentB`, its value will214/// // be fetched as well.215/// fn optional_component_query(query: Query<(&ComponentA, Option<&ComponentB>)>) {216/// // ...217/// }218/// #219/// # bevy_ecs::system::assert_is_system(optional_component_query);220/// ```221///222/// Optional components can hurt performance in some cases, so please read the [performance]223/// section to learn more about them. Additionally, if you need to declare several optional224/// components, you may be interested in using [`AnyOf`].225///226/// [performance]: #performance227/// [`AnyOf`]: crate::query::AnyOf228///229/// ## Disjoint queries230///231/// A system cannot contain two queries that break Rust's mutability rules, or else it will panic232/// when initialized. This can often be fixed with the [`Without`] filter, which makes the queries233/// disjoint.234///235/// In the following example, the two queries can mutably access the same `&mut Health` component236/// if an entity has both the `Player` and `Enemy` components. Bevy will catch this and panic,237/// however, instead of breaking Rust's mutability rules:238///239/// ```should_panic240/// # use bevy_ecs::prelude::*;241/// #242/// # #[derive(Component)]243/// # struct Health;244/// #245/// # #[derive(Component)]246/// # struct Player;247/// #248/// # #[derive(Component)]249/// # struct Enemy;250/// #251/// fn randomize_health(252/// player_query: Query<&mut Health, With<Player>>,253/// enemy_query: Query<&mut Health, With<Enemy>>,254/// ) {255/// // ...256/// }257/// #258/// # bevy_ecs::system::assert_system_does_not_conflict(randomize_health);259/// ```260///261/// Adding a [`Without`] filter will disjoint the queries. In the following example, any entity262/// that has both the `Player` and `Enemy` components will be excluded from _both_ queries:263///264/// ```265/// # use bevy_ecs::prelude::*;266/// #267/// # #[derive(Component)]268/// # struct Health;269/// #270/// # #[derive(Component)]271/// # struct Player;272/// #273/// # #[derive(Component)]274/// # struct Enemy;275/// #276/// fn randomize_health(277/// player_query: Query<&mut Health, (With<Player>, Without<Enemy>)>,278/// enemy_query: Query<&mut Health, (With<Enemy>, Without<Player>)>,279/// ) {280/// // ...281/// }282/// #283/// # bevy_ecs::system::assert_system_does_not_conflict(randomize_health);284/// ```285///286/// An alternative solution to this problem would be to wrap the conflicting queries in287/// [`ParamSet`].288///289/// [`Without`]: crate::query::Without290/// [`ParamSet`]: crate::system::ParamSet291///292/// ## Whole Entity Access293///294/// [`EntityRef`] can be used in a query to gain read-only access to all components of an entity.295/// This is useful when dynamically fetching components instead of baking them into the query type.296///297/// ```298/// # use bevy_ecs::prelude::*;299/// #300/// # #[derive(Component)]301/// # struct ComponentA;302/// #303/// fn all_components_query(query: Query<(EntityRef, &ComponentA)>) {304/// // ...305/// }306/// #307/// # bevy_ecs::system::assert_is_system(all_components_query);308/// ```309///310/// As [`EntityRef`] can read any component on an entity, a query using it will conflict with *any*311/// mutable component access.312///313/// ```should_panic314/// # use bevy_ecs::prelude::*;315/// #316/// # #[derive(Component)]317/// # struct ComponentA;318/// #319/// // `EntityRef` provides read access to *all* components on an entity. When combined with320/// // `&mut ComponentA` in the same query, it creates a conflict because `EntityRef` could read321/// // `&ComponentA` while `&mut ComponentA` attempts to modify it - violating Rust's borrowing322/// // rules.323/// fn invalid_query(query: Query<(EntityRef, &mut ComponentA)>) {324/// // ...325/// }326/// #327/// # bevy_ecs::system::assert_system_does_not_conflict(invalid_query);328/// ```329///330/// It is strongly advised to couple [`EntityRef`] queries with the use of either [`With`] /331/// [`Without`] filters or [`ParamSet`]s. Not only does this improve the performance and332/// parallelization of the system, but it enables systems to gain mutable access to other333/// components:334///335/// ```336/// # use bevy_ecs::prelude::*;337/// #338/// # #[derive(Component)]339/// # struct ComponentA;340/// #341/// # #[derive(Component)]342/// # struct ComponentB;343/// #344/// // The first query only reads entities that have `ComponentA`, while the second query only345/// // modifies entities that *don't* have `ComponentA`. Because neither query will access the same346/// // entity, this system does not conflict.347/// fn disjoint_query(348/// query_a: Query<EntityRef, With<ComponentA>>,349/// query_b: Query<&mut ComponentB, Without<ComponentA>>,350/// ) {351/// // ...352/// }353/// #354/// # bevy_ecs::system::assert_system_does_not_conflict(disjoint_query);355/// ```356///357/// The fundamental rule: [`EntityRef`]'s ability to read all components means it can never358/// coexist with mutable access. [`With`] / [`Without`] filters can guarantee this by keeping the359/// queries on completely separate entities.360///361/// [`EntityRef`]: crate::world::EntityRef362/// [`With`]: crate::query::With363///364/// # Accessing query items365///366/// The following table summarizes the behavior of safe methods that can be used to get query367/// items:368///369/// |Query methods|Effect|370/// |-|-|371/// |[`iter`]\[[`_mut`][`iter_mut`]\]|Returns an iterator over all query items.|372/// |[`iter[_mut]().for_each()`][`for_each`],<br />[`par_iter`]\[[`_mut`][`par_iter_mut`]\]|Runs a specified function for each query item.|373/// |[`iter_many`]\[[`_unique`][`iter_many_unique`]\]\[[`_mut`][`iter_many_mut`]\]|Iterates over query items that match a list of entities.|374/// |[`iter_combinations`]\[[`_mut`][`iter_combinations_mut`]\]|Iterates over all combinations of query items.|375/// |[`single`](Self::single)\[[`_mut`][`single_mut`]\]|Returns a single query item if only one exists.|376/// |[`get`]\[[`_mut`][`get_mut`]\]|Returns the query item for a specified entity.|377/// |[`get_many`]\[[`_unique`][`get_many_unique`]\]\[[`_mut`][`get_many_mut`]\]|Returns all query items that match a list of entities.|378///379/// There are two methods for each type of query operation: immutable and mutable (ending with `_mut`).380/// When using immutable methods, the query items returned are of type [`ROQueryItem`], a read-only version of the query item.381/// In this circumstance, every mutable reference in the query fetch type parameter is substituted by a shared reference.382///383/// [`iter`]: Self::iter384/// [`iter_mut`]: Self::iter_mut385/// [`for_each`]: #iteratorfor_each386/// [`par_iter`]: Self::par_iter387/// [`par_iter_mut`]: Self::par_iter_mut388/// [`iter_many`]: Self::iter_many389/// [`iter_many_unique`]: Self::iter_many_unique390/// [`iter_many_mut`]: Self::iter_many_mut391/// [`iter_combinations`]: Self::iter_combinations392/// [`iter_combinations_mut`]: Self::iter_combinations_mut393/// [`single_mut`]: Self::single_mut394/// [`get`]: Self::get395/// [`get_mut`]: Self::get_mut396/// [`get_many`]: Self::get_many397/// [`get_many_unique`]: Self::get_many_unique398/// [`get_many_mut`]: Self::get_many_mut399///400/// # Performance401///402/// Creating a `Query` is a low-cost constant operation. Iterating it, on the other hand, fetches403/// data from the world and generates items, which can have a significant computational cost.404///405/// Two systems cannot be executed in parallel if both access the same component type where at406/// least one of the accesses is mutable. Because of this, it is recommended for queries to only407/// fetch mutable access to components when necessary, since immutable access can be parallelized.408///409/// Query filters ([`With`] / [`Without`]) can improve performance because they narrow the kinds of410/// entities that can be fetched. Systems that access fewer kinds of entities are more likely to be411/// parallelized by the scheduler.412///413/// On the other hand, be careful using optional components (`Option<&ComponentA>`) and414/// [`EntityRef`] because they broaden the amount of entities kinds that can be accessed. This is415/// especially true of a query that _only_ fetches optional components or [`EntityRef`], as the416/// query would iterate over all entities in the world.417///418/// There are two types of [component storage types]: [`Table`] and [`SparseSet`]. [`Table`] offers419/// fast iteration speeds, but slower insertion and removal speeds. [`SparseSet`] is the opposite:420/// it offers fast component insertion and removal speeds, but slower iteration speeds.421///422/// The following table compares the computational complexity of the various methods and423/// operations, where:424///425/// - **n** is the number of entities that match the query.426/// - **r** is the number of elements in a combination.427/// - **k** is the number of involved entities in the operation.428/// - **a** is the number of archetypes in the world.429/// - **C** is the [binomial coefficient], used to count combinations. <sub>n</sub>C<sub>r</sub> is430/// read as "*n* choose *r*" and is equivalent to the number of distinct unordered subsets of *r*431/// elements that can be taken from a set of *n* elements.432///433/// |Query operation|Computational complexity|434/// |-|-|435/// |[`iter`]\[[`_mut`][`iter_mut`]\]|O(n)|436/// |[`iter[_mut]().for_each()`][`for_each`],<br/>[`par_iter`]\[[`_mut`][`par_iter_mut`]\]|O(n)|437/// |[`iter_many`]\[[`_mut`][`iter_many_mut`]\]|O(k)|438/// |[`iter_combinations`]\[[`_mut`][`iter_combinations_mut`]\]|O(<sub>n</sub>C<sub>r</sub>)|439/// |[`single`](Self::single)\[[`_mut`][`single_mut`]\]|O(a)|440/// |[`get`]\[[`_mut`][`get_mut`]\]|O(1)|441/// |[`get_many`]|O(k)|442/// |[`get_many_mut`]|O(k<sup>2</sup>)|443/// |Archetype-based filtering ([`With`], [`Without`], [`Or`])|O(a)|444/// |Change detection filtering ([`Added`], [`Changed`], [`Spawned`])|O(a + n)|445///446/// [component storage types]: crate::component::StorageType447/// [`Table`]: crate::storage::Table448/// [`SparseSet`]: crate::storage::SparseSet449/// [binomial coefficient]: https://en.wikipedia.org/wiki/Binomial_coefficient450/// [`Or`]: crate::query::Or451/// [`Added`]: crate::query::Added452/// [`Changed`]: crate::query::Changed453/// [`Spawned`]: crate::query::Spawned454///455/// # `Iterator::for_each`456///457/// The `for_each` methods appear to be generally faster than `for`-loops when run on worlds with458/// high archetype fragmentation, and may enable additional optimizations like [autovectorization]. It459/// is strongly advised to only use [`Iterator::for_each`] if it tangibly improves performance.460/// *Always* profile or benchmark before and after the change!461///462/// ```rust463/// # use bevy_ecs::prelude::*;464/// #465/// # #[derive(Component)]466/// # struct ComponentA;467/// #468/// fn system(query: Query<&ComponentA>) {469/// // This may result in better performance...470/// query.iter().for_each(|component| {471/// // ...472/// });473///474/// // ...than this. Always benchmark to validate the difference!475/// for component in query.iter() {476/// // ...477/// }478/// }479/// #480/// # bevy_ecs::system::assert_is_system(system);481/// ```482///483/// [autovectorization]: https://en.wikipedia.org/wiki/Automatic_vectorization484pub struct Query<'world, 'state, D: QueryData, F: QueryFilter = ()> {485// SAFETY: Must have access to the components registered in `state`.486world: UnsafeWorldCell<'world>,487state: &'state QueryState<D, F>,488last_run: Tick,489this_run: Tick,490}491492impl<D: ReadOnlyQueryData, F: QueryFilter> Clone for Query<'_, '_, D, F> {493fn clone(&self) -> Self {494*self495}496}497498impl<D: ReadOnlyQueryData, F: QueryFilter> Copy for Query<'_, '_, D, F> {}499500impl<D: QueryData, F: QueryFilter> core::fmt::Debug for Query<'_, '_, D, F> {501fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {502f.debug_struct("Query")503.field("matched_entities", &self.iter().count())504.field("state", &self.state)505.field("last_run", &self.last_run)506.field("this_run", &self.this_run)507.field("world", &self.world)508.finish()509}510}511512impl<'w, 's, D: QueryData, F: QueryFilter> Query<'w, 's, D, F> {513/// Creates a new query.514///515/// # Safety516///517/// * This will create a query that could violate memory safety rules. Make sure that this is only518/// called in ways that ensure the queries have unique mutable access.519/// * `world` must be the world used to create `state`.520#[inline]521pub(crate) unsafe fn new(522world: UnsafeWorldCell<'w>,523state: &'s QueryState<D, F>,524last_run: Tick,525this_run: Tick,526) -> Self {527Self {528world,529state,530last_run,531this_run,532}533}534535/// Returns another `Query` from this that fetches the read-only version of the query items.536///537/// For example, `Query<(&mut D1, &D2, &mut D3), With<F>>` will become `Query<(&D1, &D2, &D3), With<F>>`.538/// This can be useful when working around the borrow checker,539/// or reusing functionality between systems via functions that accept query types.540///541/// # See also542///543/// [`into_readonly`](Self::into_readonly) for a version that consumes the `Query` to return one with the full `'world` lifetime.544pub fn as_readonly(&self) -> Query<'_, 's, D::ReadOnly, F> {545// SAFETY: The reborrowed query is converted to read-only, so it cannot perform mutable access,546// and the original query is held with a shared borrow, so it cannot perform mutable access either.547unsafe { self.reborrow_unsafe() }.into_readonly()548}549550/// Returns another `Query` from this does not return any data, which can be faster.551fn as_nop(&self) -> Query<'_, 's, NopWorldQuery<D>, F> {552let new_state = self.state.as_nop();553// SAFETY:554// - The reborrowed query is converted to read-only, so it cannot perform mutable access,555// and the original query is held with a shared borrow, so it cannot perform mutable access either.556// Note that although `NopWorldQuery` itself performs *no* access and could soundly alias a mutable query,557// it has the original `QueryState::component_access` and could be `transmute`d to a read-only query.558// - The world matches because it was the same one used to construct self.559unsafe { Query::new(self.world, new_state, self.last_run, self.this_run) }560}561562/// Returns another `Query` from this that fetches the read-only version of the query items.563///564/// For example, `Query<(&mut D1, &D2, &mut D3), With<F>>` will become `Query<(&D1, &D2, &D3), With<F>>`.565/// This can be useful when working around the borrow checker,566/// or reusing functionality between systems via functions that accept query types.567///568/// # See also569///570/// [`as_readonly`](Self::as_readonly) for a version that borrows the `Query` instead of consuming it.571pub fn into_readonly(self) -> Query<'w, 's, D::ReadOnly, F> {572let new_state = self.state.as_readonly();573// SAFETY:574// - This is memory safe because it turns the query immutable.575// - The world matches because it was the same one used to construct self.576unsafe { Query::new(self.world, new_state, self.last_run, self.this_run) }577}578579/// Returns a new `Query` reborrowing the access from this one. The current query will be unusable580/// while the new one exists.581///582/// # Example583///584/// For example this allows to call other methods or other systems that require an owned `Query` without585/// completely giving up ownership of it.586///587/// ```588/// # use bevy_ecs::prelude::*;589/// #590/// # #[derive(Component)]591/// # struct ComponentA;592///593/// fn helper_system(query: Query<&ComponentA>) { /* ... */}594///595/// fn system(mut query: Query<&ComponentA>) {596/// helper_system(query.reborrow());597/// // Can still use query here:598/// for component in &query {599/// // ...600/// }601/// }602/// ```603pub fn reborrow(&mut self) -> Query<'_, 's, D, F> {604// SAFETY: this query is exclusively borrowed while the new one exists, so605// no overlapping access can occur.606unsafe { self.reborrow_unsafe() }607}608609/// Returns a new `Query` reborrowing the access from this one.610/// The current query will still be usable while the new one exists, but must not be used in a way that violates aliasing.611///612/// # Safety613///614/// This function makes it possible to violate Rust's aliasing guarantees.615/// You must make sure this call does not result in a mutable or shared reference to a component with a mutable reference.616///617/// # See also618///619/// - [`reborrow`](Self::reborrow) for the safe versions.620pub unsafe fn reborrow_unsafe(&self) -> Query<'_, 's, D, F> {621// SAFETY:622// - This is memory safe because the caller ensures that there are no conflicting references.623// - The world matches because it was the same one used to construct self.624unsafe { self.copy_unsafe() }625}626627/// Returns a new `Query` copying the access from this one.628/// The current query will still be usable while the new one exists, but must not be used in a way that violates aliasing.629///630/// # Safety631///632/// This function makes it possible to violate Rust's aliasing guarantees.633/// You must make sure this call does not result in a mutable or shared reference to a component with a mutable reference.634///635/// # See also636///637/// - [`reborrow_unsafe`](Self::reborrow_unsafe) for a safer version that constrains the returned `'w` lifetime to the length of the borrow.638unsafe fn copy_unsafe(&self) -> Query<'w, 's, D, F> {639// SAFETY:640// - This is memory safe because the caller ensures that there are no conflicting references.641// - The world matches because it was the same one used to construct self.642unsafe { Query::new(self.world, self.state, self.last_run, self.this_run) }643}644645/// Returns an [`Iterator`] over the read-only query items.646///647/// This iterator is always guaranteed to return results from each matching entity once and only once.648/// Iteration order is not guaranteed.649///650/// # Example651///652/// Here, the `report_names_system` iterates over the `Player` component of every entity that contains it:653///654/// ```655/// # use bevy_ecs::prelude::*;656/// #657/// # #[derive(Component)]658/// # struct Player { name: String }659/// #660/// fn report_names_system(query: Query<&Player>) {661/// for player in &query {662/// println!("Say hello to {}!", player.name);663/// }664/// }665/// # bevy_ecs::system::assert_is_system(report_names_system);666/// ```667///668/// # See also669///670/// [`iter_mut`](Self::iter_mut) for mutable query items.671#[inline]672pub fn iter(&self) -> QueryIter<'_, 's, D::ReadOnly, F> {673self.as_readonly().into_iter()674}675676/// Returns an [`Iterator`] over the query items.677///678/// This iterator is always guaranteed to return results from each matching entity once and only once.679/// Iteration order is not guaranteed.680///681/// # Example682///683/// Here, the `gravity_system` updates the `Velocity` component of every entity that contains it:684///685/// ```686/// # use bevy_ecs::prelude::*;687/// #688/// # #[derive(Component)]689/// # struct Velocity { x: f32, y: f32, z: f32 }690/// fn gravity_system(mut query: Query<&mut Velocity>) {691/// const DELTA: f32 = 1.0 / 60.0;692/// for mut velocity in &mut query {693/// velocity.y -= 9.8 * DELTA;694/// }695/// }696/// # bevy_ecs::system::assert_is_system(gravity_system);697/// ```698///699/// # See also700///701/// [`iter`](Self::iter) for read-only query items.702#[inline]703pub fn iter_mut(&mut self) -> QueryIter<'_, 's, D, F> {704self.reborrow().into_iter()705}706707/// Returns a [`QueryCombinationIter`] over all combinations of `K` read-only query items without repetition.708///709/// This iterator is always guaranteed to return results from each unique pair of matching entities.710/// Iteration order is not guaranteed.711///712/// # Example713///714/// ```715/// # use bevy_ecs::prelude::*;716/// # #[derive(Component)]717/// # struct ComponentA;718/// #719/// fn some_system(query: Query<&ComponentA>) {720/// for [a1, a2] in query.iter_combinations() {721/// // ...722/// }723/// }724/// ```725///726/// # See also727///728/// - [`iter_combinations_mut`](Self::iter_combinations_mut) for mutable query item combinations.729/// - [`iter_combinations_inner`](Self::iter_combinations_inner) for mutable query item combinations with the full `'world` lifetime.730#[inline]731pub fn iter_combinations<const K: usize>(732&self,733) -> QueryCombinationIter<'_, 's, D::ReadOnly, F, K> {734self.as_readonly().iter_combinations_inner()735}736737/// Returns a [`QueryCombinationIter`] over all combinations of `K` query items without repetition.738///739/// This iterator is always guaranteed to return results from each unique pair of matching entities.740/// Iteration order is not guaranteed.741///742/// # Example743///744/// ```745/// # use bevy_ecs::prelude::*;746/// # #[derive(Component)]747/// # struct ComponentA;748/// fn some_system(mut query: Query<&mut ComponentA>) {749/// let mut combinations = query.iter_combinations_mut();750/// while let Some([mut a1, mut a2]) = combinations.fetch_next() {751/// // mutably access components data752/// }753/// }754/// ```755///756/// # See also757///758/// - [`iter_combinations`](Self::iter_combinations) for read-only query item combinations.759/// - [`iter_combinations_inner`](Self::iter_combinations_inner) for mutable query item combinations with the full `'world` lifetime.760#[inline]761pub fn iter_combinations_mut<const K: usize>(762&mut self,763) -> QueryCombinationIter<'_, 's, D, F, K> {764self.reborrow().iter_combinations_inner()765}766767/// Returns a [`QueryCombinationIter`] over all combinations of `K` query items without repetition.768/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.769///770/// This iterator is always guaranteed to return results from each unique pair of matching entities.771/// Iteration order is not guaranteed.772///773/// # Example774///775/// ```776/// # use bevy_ecs::prelude::*;777/// # #[derive(Component)]778/// # struct ComponentA;779/// fn some_system(query: Query<&mut ComponentA>) {780/// let mut combinations = query.iter_combinations_inner();781/// while let Some([mut a1, mut a2]) = combinations.fetch_next() {782/// // mutably access components data783/// }784/// }785/// ```786///787/// # See also788///789/// - [`iter_combinations`](Self::iter_combinations) for read-only query item combinations.790/// - [`iter_combinations_mut`](Self::iter_combinations_mut) for mutable query item combinations.791#[inline]792pub fn iter_combinations_inner<const K: usize>(self) -> QueryCombinationIter<'w, 's, D, F, K> {793// SAFETY: `self.world` has permission to access the required components.794unsafe { QueryCombinationIter::new(self.world, self.state, self.last_run, self.this_run) }795}796797/// Returns an [`Iterator`] over the read-only query items generated from an [`Entity`] list.798///799/// Items are returned in the order of the list of entities, and may not be unique if the input800/// doesn't guarantee uniqueness. Entities that don't match the query are skipped.801///802/// # Example803///804/// ```805/// # use bevy_ecs::prelude::*;806/// # #[derive(Component)]807/// # struct Counter {808/// # value: i32809/// # }810/// #811/// // A component containing an entity list.812/// #[derive(Component)]813/// struct Friends {814/// list: Vec<Entity>,815/// }816///817/// fn system(818/// friends_query: Query<&Friends>,819/// counter_query: Query<&Counter>,820/// ) {821/// for friends in &friends_query {822/// for counter in counter_query.iter_many(&friends.list) {823/// println!("Friend's counter: {}", counter.value);824/// }825/// }826/// }827/// # bevy_ecs::system::assert_is_system(system);828/// ```829///830/// # See also831///832/// - [`iter_many_mut`](Self::iter_many_mut) to get mutable query items.833/// - [`iter_many_inner`](Self::iter_many_inner) to get mutable query items with the full `'world` lifetime.834#[inline]835pub fn iter_many<EntityList: IntoIterator<Item: EntityEquivalent>>(836&self,837entities: EntityList,838) -> QueryManyIter<'_, 's, D::ReadOnly, F, EntityList::IntoIter> {839self.as_readonly().iter_many_inner(entities)840}841842/// Returns an iterator over the query items generated from an [`Entity`] list.843///844/// Items are returned in the order of the list of entities, and may not be unique if the input845/// doesn't guarantee uniqueness. Entities that don't match the query are skipped.846///847/// # Examples848///849/// ```850/// # use bevy_ecs::prelude::*;851/// #[derive(Component)]852/// struct Counter {853/// value: i32854/// }855///856/// #[derive(Component)]857/// struct Friends {858/// list: Vec<Entity>,859/// }860///861/// fn system(862/// friends_query: Query<&Friends>,863/// mut counter_query: Query<&mut Counter>,864/// ) {865/// for friends in &friends_query {866/// let mut iter = counter_query.iter_many_mut(&friends.list);867/// while let Some(mut counter) = iter.fetch_next() {868/// println!("Friend's counter: {}", counter.value);869/// counter.value += 1;870/// }871/// }872/// }873/// # bevy_ecs::system::assert_is_system(system);874/// ```875/// # See also876///877/// - [`iter_many`](Self::iter_many) to get read-only query items.878/// - [`iter_many_inner`](Self::iter_many_inner) to get mutable query items with the full `'world` lifetime.879#[inline]880pub fn iter_many_mut<EntityList: IntoIterator<Item: EntityEquivalent>>(881&mut self,882entities: EntityList,883) -> QueryManyIter<'_, 's, D, F, EntityList::IntoIter> {884self.reborrow().iter_many_inner(entities)885}886887/// Returns an iterator over the query items generated from an [`Entity`] list.888/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.889///890/// Items are returned in the order of the list of entities, and may not be unique if the input891/// doesn't guarantee uniqueness. Entities that don't match the query are skipped.892///893/// # See also894///895/// - [`iter_many`](Self::iter_many) to get read-only query items.896/// - [`iter_many_mut`](Self::iter_many_mut) to get mutable query items.897#[inline]898pub fn iter_many_inner<EntityList: IntoIterator<Item: EntityEquivalent>>(899self,900entities: EntityList,901) -> QueryManyIter<'w, 's, D, F, EntityList::IntoIter> {902// SAFETY: `self.world` has permission to access the required components.903unsafe {904QueryManyIter::new(905self.world,906self.state,907entities,908self.last_run,909self.this_run,910)911}912}913914/// Returns an [`Iterator`] over the unique read-only query items generated from an [`EntitySet`].915///916/// Items are returned in the order of the list of entities. Entities that don't match the query are skipped.917///918/// # Example919///920/// ```921/// # use bevy_ecs::{prelude::*, entity::{EntitySet, UniqueEntityIter}};922/// # use core::slice;923/// # #[derive(Component)]924/// # struct Counter {925/// # value: i32926/// # }927/// #928/// // `Friends` ensures that it only lists unique entities.929/// #[derive(Component)]930/// struct Friends {931/// unique_list: Vec<Entity>,932/// }933///934/// impl<'a> IntoIterator for &'a Friends {935///936/// type Item = &'a Entity;937/// type IntoIter = UniqueEntityIter<slice::Iter<'a, Entity>>;938///939/// fn into_iter(self) -> Self::IntoIter {940/// // SAFETY: `Friends` ensures that it unique_list contains only unique entities.941/// unsafe { UniqueEntityIter::from_iterator_unchecked(self.unique_list.iter()) }942/// }943/// }944///945/// fn system(946/// friends_query: Query<&Friends>,947/// counter_query: Query<&Counter>,948/// ) {949/// for friends in &friends_query {950/// for counter in counter_query.iter_many_unique(friends) {951/// println!("Friend's counter: {:?}", counter.value);952/// }953/// }954/// }955/// # bevy_ecs::system::assert_is_system(system);956/// ```957///958/// # See also959///960/// - [`iter_many_unique_mut`](Self::iter_many_unique_mut) to get mutable query items.961/// - [`iter_many_unique_inner`](Self::iter_many_unique_inner) to get with the actual "inner" world lifetime.962#[inline]963pub fn iter_many_unique<EntityList: EntitySet>(964&self,965entities: EntityList,966) -> QueryManyUniqueIter<'_, 's, D::ReadOnly, F, EntityList::IntoIter> {967self.as_readonly().iter_many_unique_inner(entities)968}969970/// Returns an iterator over the unique query items generated from an [`EntitySet`].971///972/// Items are returned in the order of the list of entities. Entities that don't match the query are skipped.973///974/// # Examples975///976/// ```977/// # use bevy_ecs::{prelude::*, entity::{EntitySet, UniqueEntityIter}};978/// # use core::slice;979/// #[derive(Component)]980/// struct Counter {981/// value: i32982/// }983///984/// // `Friends` ensures that it only lists unique entities.985/// #[derive(Component)]986/// struct Friends {987/// unique_list: Vec<Entity>,988/// }989///990/// impl<'a> IntoIterator for &'a Friends {991/// type Item = &'a Entity;992/// type IntoIter = UniqueEntityIter<slice::Iter<'a, Entity>>;993///994/// fn into_iter(self) -> Self::IntoIter {995/// // SAFETY: `Friends` ensures that it unique_list contains only unique entities.996/// unsafe { UniqueEntityIter::from_iterator_unchecked(self.unique_list.iter()) }997/// }998/// }999///1000/// fn system(1001/// friends_query: Query<&Friends>,1002/// mut counter_query: Query<&mut Counter>,1003/// ) {1004/// for friends in &friends_query {1005/// for mut counter in counter_query.iter_many_unique_mut(friends) {1006/// println!("Friend's counter: {:?}", counter.value);1007/// counter.value += 1;1008/// }1009/// }1010/// }1011/// # bevy_ecs::system::assert_is_system(system);1012/// ```1013/// # See also1014///1015/// - [`iter_many_unique`](Self::iter_many_unique) to get read-only query items.1016/// - [`iter_many_unique_inner`](Self::iter_many_unique_inner) to get with the actual "inner" world lifetime.1017#[inline]1018pub fn iter_many_unique_mut<EntityList: EntitySet>(1019&mut self,1020entities: EntityList,1021) -> QueryManyUniqueIter<'_, 's, D, F, EntityList::IntoIter> {1022self.reborrow().iter_many_unique_inner(entities)1023}10241025/// Returns an iterator over the unique query items generated from an [`EntitySet`].1026/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.1027///1028/// Items are returned in the order of the list of entities. Entities that don't match the query are skipped.1029///1030/// # Examples1031///1032/// ```1033/// # use bevy_ecs::{prelude::*, entity::{EntitySet, UniqueEntityIter}};1034/// # use core::slice;1035/// #[derive(Component)]1036/// struct Counter {1037/// value: i321038/// }1039///1040/// // `Friends` ensures that it only lists unique entities.1041/// #[derive(Component)]1042/// struct Friends {1043/// unique_list: Vec<Entity>,1044/// }1045///1046/// impl<'a> IntoIterator for &'a Friends {1047/// type Item = &'a Entity;1048/// type IntoIter = UniqueEntityIter<slice::Iter<'a, Entity>>;1049///1050/// fn into_iter(self) -> Self::IntoIter {1051/// // SAFETY: `Friends` ensures that it unique_list contains only unique entities.1052/// unsafe { UniqueEntityIter::from_iterator_unchecked(self.unique_list.iter()) }1053/// }1054/// }1055///1056/// fn system(1057/// friends_query: Query<&Friends>,1058/// mut counter_query: Query<&mut Counter>,1059/// ) {1060/// let friends = friends_query.single().unwrap();1061/// for mut counter in counter_query.iter_many_unique_inner(friends) {1062/// println!("Friend's counter: {:?}", counter.value);1063/// counter.value += 1;1064/// }1065/// }1066/// # bevy_ecs::system::assert_is_system(system);1067/// ```1068/// # See also1069///1070/// - [`iter_many_unique`](Self::iter_many_unique) to get read-only query items.1071/// - [`iter_many_unique_mut`](Self::iter_many_unique_mut) to get mutable query items.1072#[inline]1073pub fn iter_many_unique_inner<EntityList: EntitySet>(1074self,1075entities: EntityList,1076) -> QueryManyUniqueIter<'w, 's, D, F, EntityList::IntoIter> {1077// SAFETY: `self.world` has permission to access the required components.1078unsafe {1079QueryManyUniqueIter::new(1080self.world,1081self.state,1082entities,1083self.last_run,1084self.this_run,1085)1086}1087}10881089/// Returns an [`Iterator`] over the query items.1090///1091/// This iterator is always guaranteed to return results from each matching entity once and only once.1092/// Iteration order is not guaranteed.1093///1094/// # Safety1095///1096/// This function makes it possible to violate Rust's aliasing guarantees.1097/// You must make sure this call does not result in multiple mutable references to the same component.1098///1099/// # See also1100///1101/// - [`iter`](Self::iter) and [`iter_mut`](Self::iter_mut) for the safe versions.1102#[inline]1103pub unsafe fn iter_unsafe(&self) -> QueryIter<'_, 's, D, F> {1104// SAFETY: The caller promises that this will not result in multiple mutable references.1105unsafe { self.reborrow_unsafe() }.into_iter()1106}11071108/// Iterates over all possible combinations of `K` query items without repetition.1109///1110/// This iterator is always guaranteed to return results from each unique pair of matching entities.1111/// Iteration order is not guaranteed.1112///1113/// # Safety1114///1115/// This allows aliased mutability.1116/// You must make sure this call does not result in multiple mutable references to the same component.1117///1118/// # See also1119///1120/// - [`iter_combinations`](Self::iter_combinations) and [`iter_combinations_mut`](Self::iter_combinations_mut) for the safe versions.1121#[inline]1122pub unsafe fn iter_combinations_unsafe<const K: usize>(1123&self,1124) -> QueryCombinationIter<'_, 's, D, F, K> {1125// SAFETY: The caller promises that this will not result in multiple mutable references.1126unsafe { self.reborrow_unsafe() }.iter_combinations_inner()1127}11281129/// Returns an [`Iterator`] over the query items generated from an [`Entity`] list.1130///1131/// Items are returned in the order of the list of entities, and may not be unique if the input1132/// doesnn't guarantee uniqueness. Entities that don't match the query are skipped.1133///1134/// # Safety1135///1136/// This allows aliased mutability and does not check for entity uniqueness.1137/// You must make sure this call does not result in multiple mutable references to the same component.1138/// Particular care must be taken when collecting the data (rather than iterating over it one item at a time) such as via [`Iterator::collect`].1139///1140/// # See also1141///1142/// - [`iter_many_mut`](Self::iter_many_mut) to safely access the query items.1143pub unsafe fn iter_many_unsafe<EntityList: IntoIterator<Item: EntityEquivalent>>(1144&self,1145entities: EntityList,1146) -> QueryManyIter<'_, 's, D, F, EntityList::IntoIter> {1147// SAFETY: The caller promises that this will not result in multiple mutable references.1148unsafe { self.reborrow_unsafe() }.iter_many_inner(entities)1149}11501151/// Returns an [`Iterator`] over the unique query items generated from an [`Entity`] list.1152///1153/// Items are returned in the order of the list of entities. Entities that don't match the query are skipped.1154///1155/// # Safety1156///1157/// This allows aliased mutability.1158/// You must make sure this call does not result in multiple mutable references to the same component.1159///1160/// # See also1161///1162/// - [`iter_many_unique`](Self::iter_many_unique) to get read-only query items.1163/// - [`iter_many_unique_mut`](Self::iter_many_unique_mut) to get mutable query items.1164/// - [`iter_many_unique_inner`](Self::iter_many_unique_inner) to get with the actual "inner" world lifetime.1165pub unsafe fn iter_many_unique_unsafe<EntityList: EntitySet>(1166&self,1167entities: EntityList,1168) -> QueryManyUniqueIter<'_, 's, D, F, EntityList::IntoIter> {1169// SAFETY: The caller promises that this will not result in multiple mutable references.1170unsafe { self.reborrow_unsafe() }.iter_many_unique_inner(entities)1171}11721173/// Returns a parallel iterator over the query results for the given [`World`].1174///1175/// This parallel iterator is always guaranteed to return results from each matching entity once and1176/// only once. Iteration order and thread assignment is not guaranteed.1177///1178/// If the `multithreaded` feature is disabled, iterating with this operates identically to [`Iterator::for_each`]1179/// on [`QueryIter`].1180///1181/// This can only be called for read-only queries, see [`par_iter_mut`] for write-queries.1182///1183/// Note that you must use the `for_each` method to iterate over the1184/// results, see [`par_iter_mut`] for an example.1185///1186/// [`par_iter_mut`]: Self::par_iter_mut1187/// [`World`]: crate::world::World1188#[inline]1189pub fn par_iter(&self) -> QueryParIter<'_, 's, D::ReadOnly, F> {1190self.as_readonly().par_iter_inner()1191}11921193/// Returns a parallel iterator over the query results for the given [`World`].1194///1195/// This parallel iterator is always guaranteed to return results from each matching entity once and1196/// only once. Iteration order and thread assignment is not guaranteed.1197///1198/// If the `multithreaded` feature is disabled, iterating with this operates identically to [`Iterator::for_each`]1199/// on [`QueryIter`].1200///1201/// This can only be called for mutable queries, see [`par_iter`] for read-only-queries.1202///1203/// # Example1204///1205/// Here, the `gravity_system` updates the `Velocity` component of every entity that contains it:1206///1207/// ```1208/// # use bevy_ecs::prelude::*;1209/// #1210/// # #[derive(Component)]1211/// # struct Velocity { x: f32, y: f32, z: f32 }1212/// fn gravity_system(mut query: Query<&mut Velocity>) {1213/// const DELTA: f32 = 1.0 / 60.0;1214/// query.par_iter_mut().for_each(|mut velocity| {1215/// velocity.y -= 9.8 * DELTA;1216/// });1217/// }1218/// # bevy_ecs::system::assert_is_system(gravity_system);1219/// ```1220///1221/// [`par_iter`]: Self::par_iter1222/// [`World`]: crate::world::World1223#[inline]1224pub fn par_iter_mut(&mut self) -> QueryParIter<'_, 's, D, F> {1225self.reborrow().par_iter_inner()1226}12271228/// Returns a parallel iterator over the query results for the given [`World`](crate::world::World).1229/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.1230///1231/// This parallel iterator is always guaranteed to return results from each matching entity once and1232/// only once. Iteration order and thread assignment is not guaranteed.1233///1234/// If the `multithreaded` feature is disabled, iterating with this operates identically to [`Iterator::for_each`]1235/// on [`QueryIter`].1236///1237/// # Example1238///1239/// Here, the `gravity_system` updates the `Velocity` component of every entity that contains it:1240///1241/// ```1242/// # use bevy_ecs::prelude::*;1243/// #1244/// # #[derive(Component)]1245/// # struct Velocity { x: f32, y: f32, z: f32 }1246/// fn gravity_system(query: Query<&mut Velocity>) {1247/// const DELTA: f32 = 1.0 / 60.0;1248/// query.par_iter_inner().for_each(|mut velocity| {1249/// velocity.y -= 9.8 * DELTA;1250/// });1251/// }1252/// # bevy_ecs::system::assert_is_system(gravity_system);1253/// ```1254#[inline]1255pub fn par_iter_inner(self) -> QueryParIter<'w, 's, D, F> {1256QueryParIter {1257world: self.world,1258state: self.state,1259last_run: self.last_run,1260this_run: self.this_run,1261batching_strategy: BatchingStrategy::new(),1262}1263}12641265/// Returns a parallel iterator over the read-only query items generated from an [`Entity`] list.1266///1267/// Entities that don't match the query are skipped. Iteration order and thread assignment is not guaranteed.1268///1269/// If the `multithreaded` feature is disabled, iterating with this operates identically to [`Iterator::for_each`]1270/// on [`QueryManyIter`].1271///1272/// This can only be called for read-only queries. To avoid potential aliasing, there is no `par_iter_many_mut` equivalent.1273/// See [`par_iter_many_unique_mut`] for an alternative using [`EntitySet`].1274///1275/// Note that you must use the `for_each` method to iterate over the1276/// results, see [`par_iter_mut`] for an example.1277///1278/// [`par_iter_many_unique_mut`]: Self::par_iter_many_unique_mut1279/// [`par_iter_mut`]: Self::par_iter_mut1280#[inline]1281pub fn par_iter_many<EntityList: IntoIterator<Item: EntityEquivalent>>(1282&self,1283entities: EntityList,1284) -> QueryParManyIter<'_, 's, D::ReadOnly, F, EntityList::Item> {1285QueryParManyIter {1286world: self.world,1287state: self.state.as_readonly(),1288entity_list: entities.into_iter().collect(),1289last_run: self.last_run,1290this_run: self.this_run,1291batching_strategy: BatchingStrategy::new(),1292}1293}12941295/// Returns a parallel iterator over the unique read-only query items generated from an [`EntitySet`].1296///1297/// Entities that don't match the query are skipped. Iteration order and thread assignment is not guaranteed.1298///1299/// If the `multithreaded` feature is disabled, iterating with this operates identically to [`Iterator::for_each`]1300/// on [`QueryManyUniqueIter`].1301///1302/// This can only be called for read-only queries, see [`par_iter_many_unique_mut`] for write-queries.1303///1304/// Note that you must use the `for_each` method to iterate over the1305/// results, see [`par_iter_mut`] for an example.1306///1307/// [`par_iter_many_unique_mut`]: Self::par_iter_many_unique_mut1308/// [`par_iter_mut`]: Self::par_iter_mut1309#[inline]1310pub fn par_iter_many_unique<EntityList: EntitySet<Item: Sync>>(1311&self,1312entities: EntityList,1313) -> QueryParManyUniqueIter<'_, 's, D::ReadOnly, F, EntityList::Item> {1314QueryParManyUniqueIter {1315world: self.world,1316state: self.state.as_readonly(),1317entity_list: entities.into_iter().collect(),1318last_run: self.last_run,1319this_run: self.this_run,1320batching_strategy: BatchingStrategy::new(),1321}1322}13231324/// Returns a parallel iterator over the unique query items generated from an [`EntitySet`].1325///1326/// Entities that don't match the query are skipped. Iteration order and thread assignment is not guaranteed.1327///1328/// If the `multithreaded` feature is disabled, iterating with this operates identically to [`Iterator::for_each`]1329/// on [`QueryManyUniqueIter`].1330///1331/// This can only be called for mutable queries, see [`par_iter_many_unique`] for read-only-queries.1332///1333/// Note that you must use the `for_each` method to iterate over the1334/// results, see [`par_iter_mut`] for an example.1335///1336/// [`par_iter_many_unique`]: Self::par_iter_many_unique1337/// [`par_iter_mut`]: Self::par_iter_mut1338#[inline]1339pub fn par_iter_many_unique_mut<EntityList: EntitySet<Item: Sync>>(1340&mut self,1341entities: EntityList,1342) -> QueryParManyUniqueIter<'_, 's, D, F, EntityList::Item> {1343QueryParManyUniqueIter {1344world: self.world,1345state: self.state,1346entity_list: entities.into_iter().collect(),1347last_run: self.last_run,1348this_run: self.this_run,1349batching_strategy: BatchingStrategy::new(),1350}1351}13521353/// Returns the read-only query item for the given [`Entity`].1354///1355/// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.1356///1357/// This is always guaranteed to run in `O(1)` time.1358///1359/// # Example1360///1361/// Here, `get` is used to retrieve the exact query item of the entity specified by the `SelectedCharacter` resource.1362///1363/// ```1364/// # use bevy_ecs::prelude::*;1365/// #1366/// # #[derive(Resource)]1367/// # struct SelectedCharacter { entity: Entity }1368/// # #[derive(Component)]1369/// # struct Character { name: String }1370/// #1371/// fn print_selected_character_name_system(1372/// query: Query<&Character>,1373/// selection: Res<SelectedCharacter>1374/// )1375/// {1376/// if let Ok(selected_character) = query.get(selection.entity) {1377/// println!("{}", selected_character.name);1378/// }1379/// }1380/// # bevy_ecs::system::assert_is_system(print_selected_character_name_system);1381/// ```1382///1383/// # See also1384///1385/// - [`get_mut`](Self::get_mut) to get a mutable query item.1386#[inline]1387pub fn get(&self, entity: Entity) -> Result<ROQueryItem<'_, 's, D>, QueryEntityError> {1388self.as_readonly().get_inner(entity)1389}13901391/// Returns the read-only query items for the given array of [`Entity`].1392///1393/// The returned query items are in the same order as the input.1394/// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.1395/// The elements of the array do not need to be unique, unlike `get_many_mut`.1396///1397/// # Examples1398///1399/// ```1400/// use bevy_ecs::prelude::*;1401/// use bevy_ecs::query::QueryEntityError;1402///1403/// #[derive(Component, PartialEq, Debug)]1404/// struct A(usize);1405///1406/// let mut world = World::new();1407/// let entity_vec: Vec<Entity> = (0..3).map(|i| world.spawn(A(i)).id()).collect();1408/// let entities: [Entity; 3] = entity_vec.try_into().unwrap();1409///1410/// world.spawn(A(73));1411///1412/// let mut query_state = world.query::<&A>();1413/// let query = query_state.query(&world);1414///1415/// let component_values = query.get_many(entities).unwrap();1416///1417/// assert_eq!(component_values, [&A(0), &A(1), &A(2)]);1418///1419/// let wrong_entity = Entity::from_raw_u32(365).unwrap();1420///1421/// assert_eq!(1422/// match query.get_many([wrong_entity]).unwrap_err() {1423/// QueryEntityError::EntityDoesNotExist(error) => error.entity,1424/// _ => panic!(),1425/// },1426/// wrong_entity1427/// );1428/// ```1429///1430/// # See also1431///1432/// - [`get_many_mut`](Self::get_many_mut) to get mutable query items.1433/// - [`get_many_unique`](Self::get_many_unique) to only handle unique inputs.1434#[inline]1435pub fn get_many<const N: usize>(1436&self,1437entities: [Entity; N],1438) -> Result<[ROQueryItem<'_, 's, D>; N], QueryEntityError> {1439// Note that we call a separate `*_inner` method from `get_many_mut`1440// because we don't need to check for duplicates.1441self.as_readonly().get_many_inner(entities)1442}14431444/// Returns the read-only query items for the given [`UniqueEntityArray`].1445///1446/// The returned query items are in the same order as the input.1447/// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.1448///1449/// # Examples1450///1451/// ```1452/// use bevy_ecs::{prelude::*, query::QueryEntityError, entity::{EntitySetIterator, UniqueEntityArray, UniqueEntityVec}};1453///1454/// #[derive(Component, PartialEq, Debug)]1455/// struct A(usize);1456///1457/// let mut world = World::new();1458/// let entity_set: UniqueEntityVec = world.spawn_batch((0..3).map(A)).collect_set();1459/// let entity_set: UniqueEntityArray<3> = entity_set.try_into().unwrap();1460///1461/// world.spawn(A(73));1462///1463/// let mut query_state = world.query::<&A>();1464/// let query = query_state.query(&world);1465///1466/// let component_values = query.get_many_unique(entity_set).unwrap();1467///1468/// assert_eq!(component_values, [&A(0), &A(1), &A(2)]);1469///1470/// let wrong_entity = Entity::from_raw_u32(365).unwrap();1471///1472/// assert_eq!(1473/// match query.get_many_unique(UniqueEntityArray::from([wrong_entity])).unwrap_err() {1474/// QueryEntityError::EntityDoesNotExist(error) => error.entity,1475/// _ => panic!(),1476/// },1477/// wrong_entity1478/// );1479/// ```1480///1481/// # See also1482///1483/// - [`get_many_unique_mut`](Self::get_many_mut) to get mutable query items.1484/// - [`get_many`](Self::get_many) to handle inputs with duplicates.1485#[inline]1486pub fn get_many_unique<const N: usize>(1487&self,1488entities: UniqueEntityArray<N>,1489) -> Result<[ROQueryItem<'_, 's, D>; N], QueryEntityError> {1490self.as_readonly().get_many_unique_inner(entities)1491}14921493/// Returns the query item for the given [`Entity`].1494///1495/// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.1496///1497/// This is always guaranteed to run in `O(1)` time.1498///1499/// # Example1500///1501/// Here, `get_mut` is used to retrieve the exact query item of the entity specified by the `PoisonedCharacter` resource.1502///1503/// ```1504/// # use bevy_ecs::prelude::*;1505/// #1506/// # #[derive(Resource)]1507/// # struct PoisonedCharacter { character_id: Entity }1508/// # #[derive(Component)]1509/// # struct Health(u32);1510/// #1511/// fn poison_system(mut query: Query<&mut Health>, poisoned: Res<PoisonedCharacter>) {1512/// if let Ok(mut health) = query.get_mut(poisoned.character_id) {1513/// health.0 -= 1;1514/// }1515/// }1516/// # bevy_ecs::system::assert_is_system(poison_system);1517/// ```1518///1519/// # See also1520///1521/// - [`get`](Self::get) to get a read-only query item.1522#[inline]1523pub fn get_mut(&mut self, entity: Entity) -> Result<D::Item<'_, 's>, QueryEntityError> {1524self.reborrow().get_inner(entity)1525}15261527/// Returns the query item for the given [`Entity`].1528/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.1529///1530/// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.1531///1532/// This is always guaranteed to run in `O(1)` time.1533///1534/// # See also1535///1536/// - [`get_mut`](Self::get_mut) to get the item using a mutable borrow of the [`Query`].1537#[inline]1538pub fn get_inner(self, entity: Entity) -> Result<D::Item<'w, 's>, QueryEntityError> {1539// SAFETY: system runs without conflicts with other systems.1540// same-system queries have runtime borrow checks when they conflict1541unsafe {1542let location = self1543.world1544.entities()1545.get(entity)1546.ok_or(EntityDoesNotExistError::new(entity, self.world.entities()))?;1547if !self1548.state1549.matched_archetypes1550.contains(location.archetype_id.index())1551{1552return Err(QueryEntityError::QueryDoesNotMatch(1553entity,1554location.archetype_id,1555));1556}1557let archetype = self1558.world1559.archetypes()1560.get(location.archetype_id)1561.debug_checked_unwrap();1562let mut fetch = D::init_fetch(1563self.world,1564&self.state.fetch_state,1565self.last_run,1566self.this_run,1567);1568let mut filter = F::init_fetch(1569self.world,1570&self.state.filter_state,1571self.last_run,1572self.this_run,1573);15741575let table = self1576.world1577.storages()1578.tables1579.get(location.table_id)1580.debug_checked_unwrap();1581D::set_archetype(&mut fetch, &self.state.fetch_state, archetype, table);1582F::set_archetype(&mut filter, &self.state.filter_state, archetype, table);15831584if F::filter_fetch(1585&self.state.filter_state,1586&mut filter,1587entity,1588location.table_row,1589) {1590Ok(D::fetch(1591&self.state.fetch_state,1592&mut fetch,1593entity,1594location.table_row,1595))1596} else {1597Err(QueryEntityError::QueryDoesNotMatch(1598entity,1599location.archetype_id,1600))1601}1602}1603}16041605/// Returns the query items for the given array of [`Entity`].1606///1607/// The returned query items are in the same order as the input.1608/// In case of a nonexisting entity, duplicate entities or mismatched component, a [`QueryEntityError`] is returned instead.1609///1610/// # Examples1611///1612/// ```1613/// use bevy_ecs::prelude::*;1614/// use bevy_ecs::query::QueryEntityError;1615///1616/// #[derive(Component, PartialEq, Debug)]1617/// struct A(usize);1618///1619/// let mut world = World::new();1620///1621/// let entities: Vec<Entity> = (0..3).map(|i| world.spawn(A(i)).id()).collect();1622/// let entities: [Entity; 3] = entities.try_into().unwrap();1623///1624/// world.spawn(A(73));1625/// let wrong_entity = Entity::from_raw_u32(57).unwrap();1626/// let invalid_entity = world.spawn_empty().id();1627///1628///1629/// let mut query_state = world.query::<&mut A>();1630/// let mut query = query_state.query_mut(&mut world);1631///1632/// let mut mutable_component_values = query.get_many_mut(entities).unwrap();1633///1634/// for mut a in &mut mutable_component_values {1635/// a.0 += 5;1636/// }1637///1638/// let component_values = query.get_many(entities).unwrap();1639///1640/// assert_eq!(component_values, [&A(5), &A(6), &A(7)]);1641///1642/// assert_eq!(1643/// match query1644/// .get_many_mut([wrong_entity])1645/// .unwrap_err()1646/// {1647/// QueryEntityError::EntityDoesNotExist(error) => error.entity,1648/// _ => panic!(),1649/// },1650/// wrong_entity1651/// );1652/// assert_eq!(1653/// match query1654/// .get_many_mut([invalid_entity])1655/// .unwrap_err()1656/// {1657/// QueryEntityError::QueryDoesNotMatch(entity, _) => entity,1658/// _ => panic!(),1659/// },1660/// invalid_entity1661/// );1662/// assert_eq!(1663/// query1664/// .get_many_mut([entities[0], entities[0]])1665/// .unwrap_err(),1666/// QueryEntityError::AliasedMutability(entities[0])1667/// );1668/// ```1669/// # See also1670///1671/// - [`get_many`](Self::get_many) to get read-only query items without checking for duplicate entities.1672#[inline]1673pub fn get_many_mut<const N: usize>(1674&mut self,1675entities: [Entity; N],1676) -> Result<[D::Item<'_, 's>; N], QueryEntityError> {1677self.reborrow().get_many_mut_inner(entities)1678}16791680/// Returns the query items for the given [`UniqueEntityArray`].1681///1682/// The returned query items are in the same order as the input.1683/// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.1684///1685/// # Examples1686///1687/// ```1688/// use bevy_ecs::{prelude::*, query::QueryEntityError, entity::{EntitySetIterator, UniqueEntityArray, UniqueEntityVec}};1689///1690/// #[derive(Component, PartialEq, Debug)]1691/// struct A(usize);1692///1693/// let mut world = World::new();1694///1695/// let entity_set: UniqueEntityVec = world.spawn_batch((0..3).map(A)).collect_set();1696/// let entity_set: UniqueEntityArray<3> = entity_set.try_into().unwrap();1697///1698/// world.spawn(A(73));1699/// let wrong_entity = Entity::from_raw_u32(57).unwrap();1700/// let invalid_entity = world.spawn_empty().id();1701///1702///1703/// let mut query_state = world.query::<&mut A>();1704/// let mut query = query_state.query_mut(&mut world);1705///1706/// let mut mutable_component_values = query.get_many_unique_mut(entity_set).unwrap();1707///1708/// for mut a in &mut mutable_component_values {1709/// a.0 += 5;1710/// }1711///1712/// let component_values = query.get_many_unique(entity_set).unwrap();1713///1714/// assert_eq!(component_values, [&A(5), &A(6), &A(7)]);1715///1716/// assert_eq!(1717/// match query1718/// .get_many_unique_mut(UniqueEntityArray::from([wrong_entity]))1719/// .unwrap_err()1720/// {1721/// QueryEntityError::EntityDoesNotExist(error) => error.entity,1722/// _ => panic!(),1723/// },1724/// wrong_entity1725/// );1726/// assert_eq!(1727/// match query1728/// .get_many_unique_mut(UniqueEntityArray::from([invalid_entity]))1729/// .unwrap_err()1730/// {1731/// QueryEntityError::QueryDoesNotMatch(entity, _) => entity,1732/// _ => panic!(),1733/// },1734/// invalid_entity1735/// );1736/// ```1737/// # See also1738///1739/// - [`get_many_unique`](Self::get_many) to get read-only query items.1740#[inline]1741pub fn get_many_unique_mut<const N: usize>(1742&mut self,1743entities: UniqueEntityArray<N>,1744) -> Result<[D::Item<'_, 's>; N], QueryEntityError> {1745self.reborrow().get_many_unique_inner(entities)1746}17471748/// Returns the query items for the given array of [`Entity`].1749/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.1750///1751/// The returned query items are in the same order as the input.1752/// In case of a nonexisting entity, duplicate entities or mismatched component, a [`QueryEntityError`] is returned instead.1753///1754/// # See also1755///1756/// - [`get_many`](Self::get_many) to get read-only query items without checking for duplicate entities.1757/// - [`get_many_mut`](Self::get_many_mut) to get items using a mutable reference.1758/// - [`get_many_inner`](Self::get_many_mut_inner) to get read-only query items with the actual "inner" world lifetime.1759#[inline]1760pub fn get_many_mut_inner<const N: usize>(1761self,1762entities: [Entity; N],1763) -> Result<[D::Item<'w, 's>; N], QueryEntityError> {1764// Verify that all entities are unique1765for i in 0..N {1766for j in 0..i {1767if entities[i] == entities[j] {1768return Err(QueryEntityError::AliasedMutability(entities[i]));1769}1770}1771}1772// SAFETY: All entities are unique, so the results don't alias.1773unsafe { self.get_many_impl(entities) }1774}17751776/// Returns the query items for the given array of [`Entity`].1777/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.1778///1779/// The returned query items are in the same order as the input.1780/// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.1781///1782/// # See also1783///1784/// - [`get_many`](Self::get_many) to get read-only query items without checking for duplicate entities.1785/// - [`get_many_mut`](Self::get_many_mut) to get items using a mutable reference.1786/// - [`get_many_mut_inner`](Self::get_many_mut_inner) to get mutable query items with the actual "inner" world lifetime.1787#[inline]1788pub fn get_many_inner<const N: usize>(1789self,1790entities: [Entity; N],1791) -> Result<[D::Item<'w, 's>; N], QueryEntityError>1792where1793D: ReadOnlyQueryData,1794{1795// SAFETY: The query results are read-only, so they don't conflict if there are duplicate entities.1796unsafe { self.get_many_impl(entities) }1797}17981799/// Returns the query items for the given [`UniqueEntityArray`].1800/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.1801///1802/// The returned query items are in the same order as the input.1803/// In case of a nonexisting entity, duplicate entities or mismatched component, a [`QueryEntityError`] is returned instead.1804///1805/// # See also1806///1807/// - [`get_many_unique`](Self::get_many_unique) to get read-only query items without checking for duplicate entities.1808/// - [`get_many_unique_mut`](Self::get_many_unique_mut) to get items using a mutable reference.1809#[inline]1810pub fn get_many_unique_inner<const N: usize>(1811self,1812entities: UniqueEntityArray<N>,1813) -> Result<[D::Item<'w, 's>; N], QueryEntityError> {1814// SAFETY: All entities are unique, so the results don't alias.1815unsafe { self.get_many_impl(entities.into_inner()) }1816}18171818/// Returns the query items for the given array of [`Entity`].1819/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.1820///1821/// # Safety1822///1823/// The caller must ensure that the query data returned for the entities does not conflict,1824/// either because they are all unique or because the data is read-only.1825unsafe fn get_many_impl<const N: usize>(1826self,1827entities: [Entity; N],1828) -> Result<[D::Item<'w, 's>; N], QueryEntityError> {1829let mut values = [(); N].map(|_| MaybeUninit::uninit());18301831for (value, entity) in core::iter::zip(&mut values, entities) {1832// SAFETY: The caller asserts that the results don't alias1833let item = unsafe { self.copy_unsafe() }.get_inner(entity)?;1834*value = MaybeUninit::new(item);1835}18361837// SAFETY: Each value has been fully initialized.1838Ok(values.map(|x| unsafe { x.assume_init() }))1839}18401841/// Returns the query item for the given [`Entity`].1842///1843/// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.1844///1845/// This is always guaranteed to run in `O(1)` time.1846///1847/// # Safety1848///1849/// This function makes it possible to violate Rust's aliasing guarantees.1850/// You must make sure this call does not result in multiple mutable references to the same component.1851///1852/// # See also1853///1854/// - [`get_mut`](Self::get_mut) for the safe version.1855#[inline]1856pub unsafe fn get_unchecked(1857&self,1858entity: Entity,1859) -> Result<D::Item<'_, 's>, QueryEntityError> {1860// SAFETY: The caller promises that this will not result in multiple mutable references.1861unsafe { self.reborrow_unsafe() }.get_inner(entity)1862}18631864/// Returns a single read-only query item when there is exactly one entity matching the query.1865///1866/// If the number of query items is not exactly one, a [`QuerySingleError`] is returned instead.1867///1868/// # Example1869///1870/// ```1871/// # use bevy_ecs::prelude::*;1872/// # use bevy_ecs::query::QuerySingleError;1873/// # #[derive(Component)]1874/// # struct PlayerScore(i32);1875/// fn player_scoring_system(query: Query<&PlayerScore>) {1876/// match query.single() {1877/// Ok(PlayerScore(score)) => {1878/// println!("Score: {}", score);1879/// }1880/// Err(QuerySingleError::NoEntities(_)) => {1881/// println!("Error: There is no player!");1882/// }1883/// Err(QuerySingleError::MultipleEntities(_)) => {1884/// println!("Error: There is more than one player!");1885/// }1886/// }1887/// }1888/// # bevy_ecs::system::assert_is_system(player_scoring_system);1889/// ```1890///1891/// # See also1892///1893/// - [`single_mut`](Self::single_mut) to get the mutable query item.1894#[inline]1895pub fn single(&self) -> Result<ROQueryItem<'_, 's, D>, QuerySingleError> {1896self.as_readonly().single_inner()1897}18981899/// Returns a single query item when there is exactly one entity matching the query.1900///1901/// If the number of query items is not exactly one, a [`QuerySingleError`] is returned instead.1902///1903/// # Example1904///1905/// ```1906/// # use bevy_ecs::prelude::*;1907/// #1908/// # #[derive(Component)]1909/// # struct Player;1910/// # #[derive(Component)]1911/// # struct Health(u32);1912/// #1913/// fn regenerate_player_health_system(mut query: Query<&mut Health, With<Player>>) {1914/// let mut health = query.single_mut().expect("Error: Could not find a single player.");1915/// health.0 += 1;1916/// }1917/// # bevy_ecs::system::assert_is_system(regenerate_player_health_system);1918/// ```1919///1920/// # See also1921///1922/// - [`single`](Self::single) to get the read-only query item.1923#[inline]1924pub fn single_mut(&mut self) -> Result<D::Item<'_, 's>, QuerySingleError> {1925self.reborrow().single_inner()1926}19271928/// Returns a single query item when there is exactly one entity matching the query.1929/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.1930///1931/// If the number of query items is not exactly one, a [`QuerySingleError`] is returned instead.1932///1933/// # Example1934///1935/// ```1936/// # use bevy_ecs::prelude::*;1937/// #1938/// # #[derive(Component)]1939/// # struct Player;1940/// # #[derive(Component)]1941/// # struct Health(u32);1942/// #1943/// fn regenerate_player_health_system(query: Query<&mut Health, With<Player>>) {1944/// let mut health = query.single_inner().expect("Error: Could not find a single player.");1945/// health.0 += 1;1946/// }1947/// # bevy_ecs::system::assert_is_system(regenerate_player_health_system);1948/// ```1949///1950/// # See also1951///1952/// - [`single`](Self::single) to get the read-only query item.1953/// - [`single_mut`](Self::single_mut) to get the mutable query item.1954#[inline]1955pub fn single_inner(self) -> Result<D::Item<'w, 's>, QuerySingleError> {1956let mut query = self.into_iter();1957let first = query.next();1958let extra = query.next().is_some();19591960match (first, extra) {1961(Some(r), false) => Ok(r),1962(None, _) => Err(QuerySingleError::NoEntities(DebugName::type_name::<Self>())),1963(Some(_), _) => Err(QuerySingleError::MultipleEntities(DebugName::type_name::<1964Self,1965>())),1966}1967}19681969/// Returns `true` if there are no query items.1970///1971/// This is equivalent to `self.iter().next().is_none()`, and thus the worst case runtime will be `O(n)`1972/// where `n` is the number of *potential* matches. This can be notably expensive for queries that rely1973/// on non-archetypal filters such as [`Added`], [`Changed`] or [`Spawned`] which must individually check1974/// each query result for a match.1975///1976/// # Example1977///1978/// Here, the score is increased only if an entity with a `Player` component is present in the world:1979///1980/// ```1981/// # use bevy_ecs::prelude::*;1982/// #1983/// # #[derive(Component)]1984/// # struct Player;1985/// # #[derive(Resource)]1986/// # struct Score(u32);1987/// fn update_score_system(query: Query<(), With<Player>>, mut score: ResMut<Score>) {1988/// if !query.is_empty() {1989/// score.0 += 1;1990/// }1991/// }1992/// # bevy_ecs::system::assert_is_system(update_score_system);1993/// ```1994///1995/// [`Added`]: crate::query::Added1996/// [`Changed`]: crate::query::Changed1997/// [`Spawned`]: crate::query::Spawned1998#[inline]1999pub fn is_empty(&self) -> bool {2000self.as_nop().iter().next().is_none()2001}20022003/// Returns `true` if the given [`Entity`] matches the query.2004///2005/// This is always guaranteed to run in `O(1)` time.2006///2007/// # Example2008///2009/// ```2010/// # use bevy_ecs::prelude::*;2011/// #2012/// # #[derive(Component)]2013/// # struct InRange;2014/// #2015/// # #[derive(Resource)]2016/// # struct Target {2017/// # entity: Entity,2018/// # }2019/// #2020/// fn targeting_system(in_range_query: Query<&InRange>, target: Res<Target>) {2021/// if in_range_query.contains(target.entity) {2022/// println!("Bam!")2023/// }2024/// }2025/// # bevy_ecs::system::assert_is_system(targeting_system);2026/// ```2027#[inline]2028pub fn contains(&self, entity: Entity) -> bool {2029self.as_nop().get(entity).is_ok()2030}20312032/// Counts the number of entities that match the query.2033///2034/// This is equivalent to `self.iter().count()` but may be more efficient in some cases.2035///2036/// If [`F::IS_ARCHETYPAL`](QueryFilter::IS_ARCHETYPAL) is `true`,2037/// this will do work proportional to the number of matched archetypes or tables, but will not iterate each entity.2038/// If it is `false`, it will have to do work for each entity.2039///2040/// # Example2041///2042/// ```2043/// # use bevy_ecs::prelude::*;2044/// #2045/// # #[derive(Component)]2046/// # struct InRange;2047/// #2048/// fn targeting_system(in_range_query: Query<&InRange>) {2049/// let count = in_range_query.count();2050/// println!("{count} targets in range!");2051/// }2052/// # bevy_ecs::system::assert_is_system(targeting_system);2053/// ```2054pub fn count(&self) -> usize {2055let iter = self.as_nop().into_iter();2056if F::IS_ARCHETYPAL {2057// For archetypal queries, the `size_hint()` is exact,2058// and we can get the count from the archetype and table counts.2059iter.size_hint().02060} else {2061// If we have non-archetypal filters, we have to check each entity.2062iter.count()2063}2064}20652066/// Returns a [`QueryLens`] that can be used to construct a new [`Query`] giving more2067/// restrictive access to the entities matched by the current query.2068///2069/// A transmute is valid only if `NewD` has a subset of the read, write, and required access2070/// of the current query. A precise description of the access required by each parameter2071/// type is given in the table below, but typical uses are to:2072/// * Remove components, e.g. `Query<(&A, &B)>` to `Query<&A>`.2073/// * Retrieve an existing component with reduced or equal access, e.g. `Query<&mut A>` to `Query<&A>`2074/// or `Query<&T>` to `Query<Ref<T>>`.2075/// * Add parameters with no new access, for example adding an `Entity` parameter.2076///2077/// Note that since filter terms are dropped, non-archetypal filters like2078/// [`Added`], [`Changed`] and [`Spawned`] will not be respected. To maintain or change filter2079/// terms see [`Self::transmute_lens_filtered`].2080///2081/// |`QueryData` parameter type|Access required|2082/// |----|----|2083/// |[`Entity`], [`EntityLocation`], [`SpawnDetails`], [`&Archetype`], [`Has<T>`], [`PhantomData<T>`]|No access|2084/// |[`EntityMut`]|Read and write access to all components, but no required access|2085/// |[`EntityRef`]|Read access to all components, but no required access|2086/// |`&T`, [`Ref<T>`]|Read and required access to `T`|2087/// |`&mut T`, [`Mut<T>`]|Read, write and required access to `T`|2088/// |[`Option<T>`], [`AnyOf<(D, ...)>`]|Read and write access to `T`, but no required access|2089/// |Tuples of query data and<br/>`#[derive(QueryData)]` structs|The union of the access of their subqueries|2090/// |[`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|2091///2092/// `transmute_lens` drops filter terms, but [`Self::transmute_lens_filtered`] supports returning a [`QueryLens`] with a new2093/// filter type - the access required by filter parameters are as follows.2094///2095/// |`QueryFilter` parameter type|Access required|2096/// |----|----|2097/// |[`Added<T>`], [`Changed<T>`]|Read and required access to `T`|2098/// |[`With<T>`], [`Without<T>`]|No access|2099/// |[`Or<(T, ...)>`]|Read access of the subqueries, but no required access|2100/// |Tuples of query filters and `#[derive(QueryFilter)]` structs|The union of the access of their subqueries|2101///2102/// [`Added`]: crate::query::Added2103/// [`Added<T>`]: crate::query::Added2104/// [`AnyOf<(D, ...)>`]: crate::query::AnyOf2105/// [`&Archetype`]: crate::archetype::Archetype2106/// [`Changed`]: crate::query::Changed2107/// [`Changed<T>`]: crate::query::Changed2108/// [`EntityMut`]: crate::world::EntityMut2109/// [`EntityLocation`]: crate::entity::EntityLocation2110/// [`EntityRef`]: crate::world::EntityRef2111/// [`FilteredEntityRef`]: crate::world::FilteredEntityRef2112/// [`FilteredEntityMut`]: crate::world::FilteredEntityMut2113/// [`Has<T>`]: crate::query::Has2114/// [`Mut<T>`]: crate::world::Mut2115/// [`Or<(T, ...)>`]: crate::query::Or2116/// [`QueryBuilder`]: crate::query::QueryBuilder2117/// [`Ref<T>`]: crate::world::Ref2118/// [`SpawnDetails`]: crate::query::SpawnDetails2119/// [`Spawned`]: crate::query::Spawned2120/// [`With<T>`]: crate::query::With2121/// [`Without<T>`]: crate::query::Without2122///2123/// ## Panics2124///2125/// This will panic if the access required by `NewD` is not a subset of that required by2126/// the original fetch `D`.2127///2128/// ## Example2129///2130/// ```rust2131/// # use bevy_ecs::prelude::*;2132/// # use bevy_ecs::system::QueryLens;2133/// #2134/// # #[derive(Component)]2135/// # struct A(usize);2136/// #2137/// # #[derive(Component)]2138/// # struct B(usize);2139/// #2140/// # let mut world = World::new();2141/// #2142/// # world.spawn((A(10), B(5)));2143/// #2144/// fn reusable_function(lens: &mut QueryLens<&A>) {2145/// assert_eq!(lens.query().single().unwrap().0, 10);2146/// }2147///2148/// // We can use the function in a system that takes the exact query.2149/// fn system_1(mut query: Query<&A>) {2150/// reusable_function(&mut query.as_query_lens());2151/// }2152///2153/// // We can also use it with a query that does not match exactly2154/// // by transmuting it.2155/// fn system_2(mut query: Query<(&mut A, &B)>) {2156/// let mut lens = query.transmute_lens::<&A>();2157/// reusable_function(&mut lens);2158/// }2159///2160/// # let mut schedule = Schedule::default();2161/// # schedule.add_systems((system_1, system_2));2162/// # schedule.run(&mut world);2163/// ```2164///2165/// ### Examples of valid transmutes2166///2167/// ```rust2168/// # use bevy_ecs::{2169/// # prelude::*,2170/// # archetype::Archetype,2171/// # entity::EntityLocation,2172/// # query::{QueryData, QueryFilter},2173/// # world::{FilteredEntityMut, FilteredEntityRef},2174/// # };2175/// # use std::marker::PhantomData;2176/// #2177/// # fn assert_valid_transmute<OldD: QueryData, NewD: QueryData>() {2178/// # assert_valid_transmute_filtered::<OldD, (), NewD, ()>();2179/// # }2180/// #2181/// # fn assert_valid_transmute_filtered<OldD: QueryData, OldF: QueryFilter, NewD: QueryData, NewF: QueryFilter>() {2182/// # let mut world = World::new();2183/// # // Make sure all components in the new query are initialized2184/// # let state = world.query_filtered::<NewD, NewF>();2185/// # let state = world.query_filtered::<OldD, OldF>();2186/// # state.transmute_filtered::<NewD, NewF>(&world);2187/// # }2188/// #2189/// # #[derive(Component)]2190/// # struct T;2191/// #2192/// # #[derive(Component)]2193/// # struct U;2194/// #2195/// # #[derive(Component)]2196/// # struct V;2197/// #2198/// // `&mut T` and `Mut<T>` access the same data and can be transmuted to each other,2199/// // `&T` and `Ref<T>` access the same data and can be transmuted to each other,2200/// // and mutable versions can be transmuted to read-only versions2201/// assert_valid_transmute::<&mut T, &T>();2202/// assert_valid_transmute::<&mut T, Mut<T>>();2203/// assert_valid_transmute::<Mut<T>, &mut T>();2204/// assert_valid_transmute::<&T, Ref<T>>();2205/// assert_valid_transmute::<Ref<T>, &T>();2206///2207/// // The structure can be rearranged, or subqueries dropped2208/// assert_valid_transmute::<(&T, &U), &T>();2209/// assert_valid_transmute::<((&T, &U), &V), (&T, (&U, &V))>();2210/// assert_valid_transmute::<Option<(&T, &U)>, (Option<&T>, Option<&U>)>();2211///2212/// // Queries with no access can be freely added2213/// assert_valid_transmute::<2214/// &T,2215/// (&T, Entity, EntityLocation, &Archetype, Has<U>, PhantomData<T>),2216/// >();2217///2218/// // Required access can be transmuted to optional,2219/// // and optional access can be transmuted to other optional access2220/// assert_valid_transmute::<&T, Option<&T>>();2221/// assert_valid_transmute::<AnyOf<(&mut T, &mut U)>, Option<&T>>();2222/// // Note that removing subqueries from `AnyOf` will result2223/// // in an `AnyOf` where all subqueries can yield `None`!2224/// assert_valid_transmute::<AnyOf<(&T, &U, &V)>, AnyOf<(&T, &U)>>();2225/// assert_valid_transmute::<EntityMut, Option<&mut T>>();2226///2227/// // Anything can be transmuted to `FilteredEntityRef` or `FilteredEntityMut`2228/// // This will create a `FilteredEntityMut` that only has read access to `T`2229/// assert_valid_transmute::<&T, FilteredEntityMut>();2230/// // This will create a `FilteredEntityMut` that has no access to `T`,2231/// // read access to `U`, and write access to `V`.2232/// assert_valid_transmute::<(&mut T, &mut U, &mut V), (&mut T, &U, FilteredEntityMut)>();2233///2234/// // `Added<T>` and `Changed<T>` filters have the same access as `&T` data2235/// // Remember that they are only evaluated on the transmuted query, not the original query!2236/// assert_valid_transmute_filtered::<Entity, Changed<T>, &T, ()>();2237/// assert_valid_transmute_filtered::<&mut T, (), &T, Added<T>>();2238/// // Nested inside of an `Or` filter, they have the same access as `Option<&T>`.2239/// assert_valid_transmute_filtered::<Option<&T>, (), Entity, Or<(Changed<T>, With<U>)>>();2240/// ```2241#[track_caller]2242pub fn transmute_lens<NewD: QueryData>(&mut self) -> QueryLens<'_, NewD> {2243self.transmute_lens_filtered::<NewD, ()>()2244}22452246/// Returns a [`QueryLens`] that can be used to construct a new `Query` giving more restrictive2247/// access to the entities matched by the current query.2248///2249/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.2250///2251/// See [`Self::transmute_lens`] for a description of allowed transmutes.2252///2253/// ## Panics2254///2255/// This will panic if `NewD` is not a subset of the original fetch `D`2256///2257/// ## Example2258///2259/// ```rust2260/// # use bevy_ecs::prelude::*;2261/// # use bevy_ecs::system::QueryLens;2262/// #2263/// # #[derive(Component)]2264/// # struct A(usize);2265/// #2266/// # #[derive(Component)]2267/// # struct B(usize);2268/// #2269/// # let mut world = World::new();2270/// #2271/// # world.spawn((A(10), B(5)));2272/// #2273/// fn reusable_function(mut lens: QueryLens<&A>) {2274/// assert_eq!(lens.query().single().unwrap().0, 10);2275/// }2276///2277/// // We can use the function in a system that takes the exact query.2278/// fn system_1(query: Query<&A>) {2279/// reusable_function(query.into_query_lens());2280/// }2281///2282/// // We can also use it with a query that does not match exactly2283/// // by transmuting it.2284/// fn system_2(query: Query<(&mut A, &B)>) {2285/// let mut lens = query.transmute_lens_inner::<&A>();2286/// reusable_function(lens);2287/// }2288///2289/// # let mut schedule = Schedule::default();2290/// # schedule.add_systems((system_1, system_2));2291/// # schedule.run(&mut world);2292/// ```2293///2294/// # See also2295///2296/// - [`transmute_lens`](Self::transmute_lens) to convert to a lens using a mutable borrow of the [`Query`].2297#[track_caller]2298pub fn transmute_lens_inner<NewD: QueryData>(self) -> QueryLens<'w, NewD> {2299self.transmute_lens_filtered_inner::<NewD, ()>()2300}23012302/// Equivalent to [`Self::transmute_lens`] but also includes a [`QueryFilter`] type.2303///2304/// See [`Self::transmute_lens`] for a description of allowed transmutes.2305///2306/// Note that the lens will iterate the same tables and archetypes as the original query. This means that2307/// additional archetypal query terms like [`With`](crate::query::With) and [`Without`](crate::query::Without)2308/// will not necessarily be respected and non-archetypal terms like [`Added`](crate::query::Added),2309/// [`Changed`](crate::query::Changed) and [`Spawned`](crate::query::Spawned) will only be respected if they2310/// are in the type signature.2311#[track_caller]2312pub fn transmute_lens_filtered<NewD: QueryData, NewF: QueryFilter>(2313&mut self,2314) -> QueryLens<'_, NewD, NewF> {2315self.reborrow().transmute_lens_filtered_inner()2316}23172318/// Equivalent to [`Self::transmute_lens_inner`] but also includes a [`QueryFilter`] type.2319/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.2320///2321/// See [`Self::transmute_lens`] for a description of allowed transmutes.2322///2323/// Note that the lens will iterate the same tables and archetypes as the original query. This means that2324/// additional archetypal query terms like [`With`](crate::query::With) and [`Without`](crate::query::Without)2325/// will not necessarily be respected and non-archetypal terms like [`Added`](crate::query::Added),2326/// [`Changed`](crate::query::Changed) and [`Spawned`](crate::query::Spawned) will only be respected if they2327/// are in the type signature.2328///2329/// # See also2330///2331/// - [`transmute_lens_filtered`](Self::transmute_lens_filtered) to convert to a lens using a mutable borrow of the [`Query`].2332#[track_caller]2333pub fn transmute_lens_filtered_inner<NewD: QueryData, NewF: QueryFilter>(2334self,2335) -> QueryLens<'w, NewD, NewF> {2336let state = self.state.transmute_filtered::<NewD, NewF>(self.world);2337QueryLens {2338world: self.world,2339state,2340last_run: self.last_run,2341this_run: self.this_run,2342}2343}23442345/// Gets a [`QueryLens`] with the same accesses as the existing query2346pub fn as_query_lens(&mut self) -> QueryLens<'_, D> {2347self.transmute_lens()2348}23492350/// Gets a [`QueryLens`] with the same accesses as the existing query2351///2352/// # See also2353///2354/// - [`as_query_lens`](Self::as_query_lens) to convert to a lens using a mutable borrow of the [`Query`].2355pub fn into_query_lens(self) -> QueryLens<'w, D> {2356self.transmute_lens_inner()2357}23582359/// Returns a [`QueryLens`] that can be used to get a query with the combined fetch.2360///2361/// For example, this can take a `Query<&A>` and a `Query<&B>` and return a `Query<(&A, &B)>`.2362/// The returned query will only return items with both `A` and `B`. Note that since filters2363/// are dropped, non-archetypal filters like `Added`, `Changed` and `Spawned` will not be respected.2364/// To maintain or change filter terms see `Self::join_filtered`.2365///2366/// ## Example2367///2368/// ```rust2369/// # use bevy_ecs::prelude::*;2370/// # use bevy_ecs::system::QueryLens;2371/// #2372/// # #[derive(Component)]2373/// # struct Transform;2374/// #2375/// # #[derive(Component)]2376/// # struct Player;2377/// #2378/// # #[derive(Component)]2379/// # struct Enemy;2380/// #2381/// # let mut world = World::default();2382/// # world.spawn((Transform, Player));2383/// # world.spawn((Transform, Enemy));2384///2385/// fn system(2386/// mut transforms: Query<&Transform>,2387/// mut players: Query<&Player>,2388/// mut enemies: Query<&Enemy>2389/// ) {2390/// let mut players_transforms: QueryLens<(&Transform, &Player)> = transforms.join(&mut players);2391/// for (transform, player) in &players_transforms.query() {2392/// // do something with a and b2393/// }2394///2395/// let mut enemies_transforms: QueryLens<(&Transform, &Enemy)> = transforms.join(&mut enemies);2396/// for (transform, enemy) in &enemies_transforms.query() {2397/// // do something with a and b2398/// }2399/// }2400///2401/// # let mut schedule = Schedule::default();2402/// # schedule.add_systems(system);2403/// # schedule.run(&mut world);2404/// ```2405/// ## Panics2406///2407/// This will panic if `NewD` is not a subset of the union of the original fetch `Q` and `OtherD`.2408///2409/// ## Allowed Transmutes2410///2411/// Like `transmute_lens` the query terms can be changed with some restrictions.2412/// See [`Self::transmute_lens`] for more details.2413pub fn join<'a, OtherD: QueryData, NewD: QueryData>(2414&'a mut self,2415other: &'a mut Query<OtherD>,2416) -> QueryLens<'a, NewD> {2417self.join_filtered(other)2418}24192420/// Returns a [`QueryLens`] that can be used to get a query with the combined fetch.2421/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.2422///2423/// For example, this can take a `Query<&A>` and a `Query<&B>` and return a `Query<(&A, &B)>`.2424/// The returned query will only return items with both `A` and `B`. Note that since filters2425/// are dropped, non-archetypal filters like `Added`, `Changed` and `Spawned` will not be respected.2426/// To maintain or change filter terms see `Self::join_filtered`.2427///2428/// ## Panics2429///2430/// This will panic if `NewD` is not a subset of the union of the original fetch `Q` and `OtherD`.2431///2432/// ## Allowed Transmutes2433///2434/// Like `transmute_lens` the query terms can be changed with some restrictions.2435/// See [`Self::transmute_lens`] for more details.2436///2437/// # See also2438///2439/// - [`join`](Self::join) to join using a mutable borrow of the [`Query`].2440pub fn join_inner<OtherD: QueryData, NewD: QueryData>(2441self,2442other: Query<'w, '_, OtherD>,2443) -> QueryLens<'w, NewD> {2444self.join_filtered_inner(other)2445}24462447/// Equivalent to [`Self::join`] but also includes a [`QueryFilter`] type.2448///2449/// Note that the lens with iterate a subset of the original queries' tables2450/// and archetypes. This means that additional archetypal query terms like2451/// `With` and `Without` will not necessarily be respected and non-archetypal2452/// terms like `Added`, `Changed` and `Spawned` will only be respected if they2453/// are in the type signature.2454pub fn join_filtered<2455'a,2456OtherD: QueryData,2457OtherF: QueryFilter,2458NewD: QueryData,2459NewF: QueryFilter,2460>(2461&'a mut self,2462other: &'a mut Query<OtherD, OtherF>,2463) -> QueryLens<'a, NewD, NewF> {2464self.reborrow().join_filtered_inner(other.reborrow())2465}24662467/// Equivalent to [`Self::join_inner`] but also includes a [`QueryFilter`] type.2468/// This consumes the [`Query`] to return results with the actual "inner" world lifetime.2469///2470/// Note that the lens with iterate a subset of the original queries' tables2471/// and archetypes. This means that additional archetypal query terms like2472/// `With` and `Without` will not necessarily be respected and non-archetypal2473/// terms like `Added`, `Changed` and `Spawned` will only be respected if they2474/// are in the type signature.2475///2476/// # See also2477///2478/// - [`join_filtered`](Self::join_filtered) to join using a mutable borrow of the [`Query`].2479pub fn join_filtered_inner<2480OtherD: QueryData,2481OtherF: QueryFilter,2482NewD: QueryData,2483NewF: QueryFilter,2484>(2485self,2486other: Query<'w, '_, OtherD, OtherF>,2487) -> QueryLens<'w, NewD, NewF> {2488let state = self2489.state2490.join_filtered::<OtherD, OtherF, NewD, NewF>(self.world, other.state);2491QueryLens {2492world: self.world,2493state,2494last_run: self.last_run,2495this_run: self.this_run,2496}2497}2498}24992500impl<'w, 's, D: QueryData, F: QueryFilter> IntoIterator for Query<'w, 's, D, F> {2501type Item = D::Item<'w, 's>;2502type IntoIter = QueryIter<'w, 's, D, F>;25032504fn into_iter(self) -> Self::IntoIter {2505// SAFETY:2506// - `self.world` has permission to access the required components.2507// - We consume the query, so mutable queries cannot alias.2508// Read-only queries are `Copy`, but may alias themselves.2509unsafe { QueryIter::new(self.world, self.state, self.last_run, self.this_run) }2510}2511}25122513impl<'w, 's, D: QueryData, F: QueryFilter> IntoIterator for &'w Query<'_, 's, D, F> {2514type Item = ROQueryItem<'w, 's, D>;2515type IntoIter = QueryIter<'w, 's, D::ReadOnly, F>;25162517fn into_iter(self) -> Self::IntoIter {2518self.iter()2519}2520}25212522impl<'w, 's, D: QueryData, F: QueryFilter> IntoIterator for &'w mut Query<'_, 's, D, F> {2523type Item = D::Item<'w, 's>;2524type IntoIter = QueryIter<'w, 's, D, F>;25252526fn into_iter(self) -> Self::IntoIter {2527self.iter_mut()2528}2529}25302531impl<'w, 's, D: ReadOnlyQueryData, F: QueryFilter> Query<'w, 's, D, F> {2532/// Returns an [`Iterator`] over the query items, with the actual "inner" world lifetime.2533///2534/// This can only return immutable data (mutable data will be cast to an immutable form).2535/// See [`Self::iter_mut`] for queries that contain at least one mutable component.2536///2537/// # Example2538///2539/// Here, the `report_names_system` iterates over the `Player` component of every entity2540/// that contains it:2541///2542/// ```2543/// # use bevy_ecs::prelude::*;2544/// #2545/// # #[derive(Component)]2546/// # struct Player { name: String }2547/// #2548/// fn report_names_system(query: Query<&Player>) {2549/// for player in &query {2550/// println!("Say hello to {}!", player.name);2551/// }2552/// }2553/// # bevy_ecs::system::assert_is_system(report_names_system);2554/// ```2555#[inline]2556pub fn iter_inner(&self) -> QueryIter<'w, 's, D::ReadOnly, F> {2557(*self).into_iter()2558}2559}25602561/// Type returned from [`Query::transmute_lens`] containing the new [`QueryState`].2562///2563/// Call [`query`](QueryLens::query) or [`into`](Into::into) to construct the resulting [`Query`]2564pub struct QueryLens<'w, Q: QueryData, F: QueryFilter = ()> {2565world: UnsafeWorldCell<'w>,2566state: QueryState<Q, F>,2567last_run: Tick,2568this_run: Tick,2569}25702571impl<'w, Q: QueryData, F: QueryFilter> QueryLens<'w, Q, F> {2572/// Create a [`Query`] from the underlying [`QueryState`].2573pub fn query(&mut self) -> Query<'_, '_, Q, F> {2574Query {2575world: self.world,2576state: &self.state,2577last_run: self.last_run,2578this_run: self.this_run,2579}2580}2581}25822583impl<'w, Q: ReadOnlyQueryData, F: QueryFilter> QueryLens<'w, Q, F> {2584/// Create a [`Query`] from the underlying [`QueryState`].2585/// This returns results with the actual "inner" world lifetime,2586/// so it may only be used with read-only queries to prevent mutable aliasing.2587pub fn query_inner(&self) -> Query<'w, '_, Q, F> {2588Query {2589world: self.world,2590state: &self.state,2591last_run: self.last_run,2592this_run: self.this_run,2593}2594}2595}25962597impl<'w, 's, Q: QueryData, F: QueryFilter> From<&'s mut QueryLens<'w, Q, F>>2598for Query<'s, 's, Q, F>2599{2600fn from(value: &'s mut QueryLens<'w, Q, F>) -> Query<'s, 's, Q, F> {2601value.query()2602}2603}26042605impl<'w, 'q, Q: QueryData, F: QueryFilter> From<&'q mut Query<'w, '_, Q, F>>2606for QueryLens<'q, Q, F>2607{2608fn from(value: &'q mut Query<'w, '_, Q, F>) -> QueryLens<'q, Q, F> {2609value.transmute_lens_filtered()2610}2611}26122613/// [System parameter] that provides access to single entity's components, much like [`Query::single`]/[`Query::single_mut`].2614///2615/// This [`SystemParam`](crate::system::SystemParam) fails validation if zero or more than one matching entity exists.2616/// This will cause the system to be skipped, according to the rules laid out in [`SystemParamValidationError`](crate::system::SystemParamValidationError).2617///2618/// Use [`Option<Single<D, F>>`] instead if zero or one matching entities can exist.2619///2620/// See [`Query`] for more details.2621///2622/// [System parameter]: crate::system::SystemParam2623///2624/// # Example2625/// ```2626/// # use bevy_ecs::prelude::*;2627/// #[derive(Component)]2628/// struct Boss {2629/// health: f322630/// };2631///2632/// fn hurt_boss(mut boss: Single<&mut Boss>) {2633/// boss.health -= 4.0;2634/// }2635/// ```2636/// Note that because [`Single`] implements [`Deref`] and [`DerefMut`], methods and fields like `health` can be accessed directly.2637/// You can also access the underlying data manually, by calling `.deref`/`.deref_mut`, or by using the `*` operator.2638pub struct Single<'w, 's, D: QueryData, F: QueryFilter = ()> {2639pub(crate) item: D::Item<'w, 's>,2640pub(crate) _filter: PhantomData<F>,2641}26422643impl<'w, 's, D: QueryData, F: QueryFilter> Deref for Single<'w, 's, D, F> {2644type Target = D::Item<'w, 's>;26452646fn deref(&self) -> &Self::Target {2647&self.item2648}2649}26502651impl<'w, 's, D: QueryData, F: QueryFilter> DerefMut for Single<'w, 's, D, F> {2652fn deref_mut(&mut self) -> &mut Self::Target {2653&mut self.item2654}2655}26562657impl<'w, 's, D: QueryData, F: QueryFilter> Single<'w, 's, D, F> {2658/// Returns the inner item with ownership.2659pub fn into_inner(self) -> D::Item<'w, 's> {2660self.item2661}2662}26632664/// [System parameter] that works very much like [`Query`] except it always contains at least one matching entity.2665///2666/// This [`SystemParam`](crate::system::SystemParam) fails validation if no matching entities exist.2667/// This will cause the system to be skipped, according to the rules laid out in [`SystemParamValidationError`](crate::system::SystemParamValidationError).2668///2669/// Much like [`Query::is_empty`] the worst case runtime will be `O(n)` where `n` is the number of *potential* matches.2670/// This can be notably expensive for queries that rely on non-archetypal filters such as [`Added`](crate::query::Added),2671/// [`Changed`](crate::query::Changed) of [`Spawned`](crate::query::Spawned) which must individually check each query2672/// result for a match.2673///2674/// See [`Query`] for more details.2675///2676/// [System parameter]: crate::system::SystemParam2677pub struct Populated<'w, 's, D: QueryData, F: QueryFilter = ()>(pub(crate) Query<'w, 's, D, F>);26782679impl<'w, 's, D: QueryData, F: QueryFilter> Deref for Populated<'w, 's, D, F> {2680type Target = Query<'w, 's, D, F>;26812682fn deref(&self) -> &Self::Target {2683&self.02684}2685}26862687impl<D: QueryData, F: QueryFilter> DerefMut for Populated<'_, '_, D, F> {2688fn deref_mut(&mut self) -> &mut Self::Target {2689&mut self.02690}2691}26922693impl<'w, 's, D: QueryData, F: QueryFilter> Populated<'w, 's, D, F> {2694/// Returns the inner item with ownership.2695pub fn into_inner(self) -> Query<'w, 's, D, F> {2696self.02697}2698}26992700impl<'w, 's, D: QueryData, F: QueryFilter> IntoIterator for Populated<'w, 's, D, F> {2701type Item = <Query<'w, 's, D, F> as IntoIterator>::Item;27022703type IntoIter = <Query<'w, 's, D, F> as IntoIterator>::IntoIter;27042705fn into_iter(self) -> Self::IntoIter {2706self.0.into_iter()2707}2708}27092710impl<'a, 'w, 's, D: QueryData, F: QueryFilter> IntoIterator for &'a Populated<'w, 's, D, F> {2711type Item = <&'a Query<'w, 's, D, F> as IntoIterator>::Item;27122713type IntoIter = <&'a Query<'w, 's, D, F> as IntoIterator>::IntoIter;27142715fn into_iter(self) -> Self::IntoIter {2716self.deref().into_iter()2717}2718}27192720impl<'a, 'w, 's, D: QueryData, F: QueryFilter> IntoIterator for &'a mut Populated<'w, 's, D, F> {2721type Item = <&'a mut Query<'w, 's, D, F> as IntoIterator>::Item;27222723type IntoIter = <&'a mut Query<'w, 's, D, F> as IntoIterator>::IntoIter;27242725fn into_iter(self) -> Self::IntoIter {2726self.deref_mut().into_iter()2727}2728}27292730#[cfg(test)]2731mod tests {2732use crate::{prelude::*, query::QueryEntityError};2733use alloc::vec::Vec;27342735#[test]2736fn get_many_uniqueness() {2737let mut world = World::new();27382739let entities: Vec<Entity> = (0..10).map(|_| world.spawn_empty().id()).collect();27402741let mut query_state = world.query::<Entity>();27422743// It's best to test get_many_mut_inner directly, as it is shared2744// We don't care about aliased mutability for the read-only equivalent27452746// SAFETY: Query does not access world data.2747assert!(query_state2748.query_mut(&mut world)2749.get_many_mut_inner::<10>(entities.clone().try_into().unwrap())2750.is_ok());27512752assert_eq!(2753query_state2754.query_mut(&mut world)2755.get_many_mut_inner([entities[0], entities[0]])2756.unwrap_err(),2757QueryEntityError::AliasedMutability(entities[0])2758);27592760assert_eq!(2761query_state2762.query_mut(&mut world)2763.get_many_mut_inner([entities[0], entities[1], entities[0]])2764.unwrap_err(),2765QueryEntityError::AliasedMutability(entities[0])2766);27672768assert_eq!(2769query_state2770.query_mut(&mut world)2771.get_many_mut_inner([entities[9], entities[9]])2772.unwrap_err(),2773QueryEntityError::AliasedMutability(entities[9])2774);2775}2776}277727782779