bevy_ecs/system/query.rs
1use crate::{
2 batching::BatchingStrategy,
3 component::Tick,
4 entity::Entity,
5 query::{
6 QueryCombinationIter, QueryData, QueryEntityError, QueryFilter, QueryIter, QueryManyIter,
7 QueryParIter, QuerySingleError, QueryState, ROQueryItem, ReadOnlyQueryData,
8 },
9 world::unsafe_world_cell::UnsafeWorldCell,
10};
11use std::borrow::Borrow;
12
13/// [System parameter] that provides selective access to the [`Component`] data stored in a [`World`].
14///
15/// Enables access to [entity identifiers] and [components] from a system, without the need to directly access the world.
16/// Its iterators and getter methods return *query items*.
17/// Each query item is a type containing data relative to an entity.
18///
19/// `Query` is a generic data structure that accepts two type parameters:
20///
21/// - **`D` (query data).**
22/// The type of data contained in the query item.
23/// Only entities that match the requested data will generate an item.
24/// Must implement the [`QueryData`] trait.
25/// - **`F` (query filter).**
26/// A set of conditions that determines whether query items should be kept or discarded.
27/// Must implement the [`QueryFilter`] trait.
28/// This type parameter is optional.
29///
30/// [`World`]: crate::world::World
31///
32/// # System parameter declaration
33///
34/// A query should always be declared as a system parameter.
35/// This section shows the most common idioms involving the declaration of `Query`.
36///
37/// ## Component access
38///
39/// A query defined with a reference to a component as the query fetch type parameter can be used to generate items that refer to the data of said component.
40///
41/// ```
42/// # use bevy_ecs::prelude::*;
43/// # #[derive(Component)]
44/// # struct ComponentA;
45/// # fn immutable_ref(
46/// // A component can be accessed by shared reference...
47/// query: Query<&ComponentA>
48/// # ) {}
49/// # bevy_ecs::system::assert_is_system(immutable_ref);
50///
51/// # fn mutable_ref(
52/// // ... or by mutable reference.
53/// query: Query<&mut ComponentA>
54/// # ) {}
55/// # bevy_ecs::system::assert_is_system(mutable_ref);
56/// ```
57///
58/// ## Query filtering
59///
60/// Setting the query filter type parameter will ensure that each query item satisfies the given condition.
61///
62/// ```
63/// # use bevy_ecs::prelude::*;
64/// # #[derive(Component)]
65/// # struct ComponentA;
66/// # #[derive(Component)]
67/// # struct ComponentB;
68/// # fn system(
69/// // Just `ComponentA` data will be accessed, but only for entities that also contain
70/// // `ComponentB`.
71/// query: Query<&ComponentA, With<ComponentB>>
72/// # ) {}
73/// # bevy_ecs::system::assert_is_system(system);
74/// ```
75///
76/// ## `QueryData` or `QueryFilter` tuples
77///
78/// Using tuples, each `Query` type parameter can contain multiple elements.
79///
80/// In the following example, two components are accessed simultaneously, and the query items are filtered on two conditions.
81///
82/// ```
83/// # use bevy_ecs::prelude::*;
84/// # #[derive(Component)]
85/// # struct ComponentA;
86/// # #[derive(Component)]
87/// # struct ComponentB;
88/// # #[derive(Component)]
89/// # struct ComponentC;
90/// # #[derive(Component)]
91/// # struct ComponentD;
92/// # fn immutable_ref(
93/// query: Query<(&ComponentA, &ComponentB), (With<ComponentC>, Without<ComponentD>)>
94/// # ) {}
95/// # bevy_ecs::system::assert_is_system(immutable_ref);
96/// ```
97///
98/// ## Entity identifier access
99///
100/// The identifier of an entity can be made available inside the query item by including [`Entity`] in the query fetch type parameter.
101///
102/// ```
103/// # use bevy_ecs::prelude::*;
104/// # #[derive(Component)]
105/// # struct ComponentA;
106/// # fn system(
107/// query: Query<(Entity, &ComponentA)>
108/// # ) {}
109/// # bevy_ecs::system::assert_is_system(system);
110/// ```
111///
112/// ## Optional component access
113///
114/// A component can be made optional in a query by wrapping it into an [`Option`].
115/// In this way, a query item can still be generated even if the queried entity does not contain the wrapped component.
116/// In this case, its corresponding value will be `None`.
117///
118/// ```
119/// # use bevy_ecs::prelude::*;
120/// # #[derive(Component)]
121/// # struct ComponentA;
122/// # #[derive(Component)]
123/// # struct ComponentB;
124/// # fn system(
125/// // Generates items for entities that contain `ComponentA`, and optionally `ComponentB`.
126/// query: Query<(&ComponentA, Option<&ComponentB>)>
127/// # ) {}
128/// # bevy_ecs::system::assert_is_system(system);
129/// ```
130///
131/// See the documentation for [`AnyOf`] to idiomatically declare many optional components.
132///
133/// See the [performance] section to learn more about the impact of optional components.
134///
135/// ## Disjoint queries
136///
137/// A system cannot contain two queries that break Rust's mutability rules.
138/// In this case, the [`Without`] filter can be used to disjoint them.
139///
140/// In the following example, two queries mutably access the same component.
141/// Executing this system will panic, since an entity could potentially match the two queries at the same time by having both `Player` and `Enemy` components.
142/// This would violate mutability rules.
143///
144/// ```should_panic
145/// # use bevy_ecs::prelude::*;
146/// # #[derive(Component)]
147/// # struct Health;
148/// # #[derive(Component)]
149/// # struct Player;
150/// # #[derive(Component)]
151/// # struct Enemy;
152/// #
153/// fn randomize_health(
154/// player_query: Query<&mut Health, With<Player>>,
155/// enemy_query: Query<&mut Health, With<Enemy>>,
156/// )
157/// # {}
158/// # let mut randomize_health_system = IntoSystem::into_system(randomize_health);
159/// # let mut world = World::new();
160/// # randomize_health_system.initialize(&mut world);
161/// # randomize_health_system.run((), &mut world);
162/// ```
163///
164/// Adding a `Without` filter will disjoint the queries.
165/// In this way, any entity that has both `Player` and `Enemy` components is excluded from both queries.
166///
167/// ```
168/// # use bevy_ecs::prelude::*;
169/// # #[derive(Component)]
170/// # struct Health;
171/// # #[derive(Component)]
172/// # struct Player;
173/// # #[derive(Component)]
174/// # struct Enemy;
175/// #
176/// fn randomize_health(
177/// player_query: Query<&mut Health, (With<Player>, Without<Enemy>)>,
178/// enemy_query: Query<&mut Health, (With<Enemy>, Without<Player>)>,
179/// )
180/// # {}
181/// # let mut randomize_health_system = IntoSystem::into_system(randomize_health);
182/// # let mut world = World::new();
183/// # randomize_health_system.initialize(&mut world);
184/// # randomize_health_system.run((), &mut world);
185/// ```
186///
187/// An alternative to this idiom is to wrap the conflicting queries into a [`ParamSet`](super::ParamSet).
188///
189/// ## Whole Entity Access
190///
191/// [`EntityRef`]s can be fetched from a query. This will give read-only access to any component on the entity,
192/// and can be use to dynamically fetch any component without baking it into the query type. Due to this global
193/// access to the entity, this will block any other system from parallelizing with it. As such these queries
194/// should be sparingly used.
195///
196/// ```
197/// # use bevy_ecs::prelude::*;
198/// # #[derive(Component)]
199/// # struct ComponentA;
200/// # fn system(
201/// query: Query<(EntityRef, &ComponentA)>
202/// # ) {}
203/// # bevy_ecs::system::assert_is_system(system);
204/// ```
205///
206/// As `EntityRef` can read any component on an entity, a query using it will conflict with *any* mutable
207/// access. It is strongly advised to couple `EntityRef` queries with the use of either `With`/`Without`
208/// filters or `ParamSets`. This also limits the scope of the query, which will improve iteration performance
209/// and also allows it to parallelize with other non-conflicting systems.
210///
211/// ```should_panic
212/// # use bevy_ecs::prelude::*;
213/// # #[derive(Component)]
214/// # struct ComponentA;
215/// # fn system(
216/// // This will panic!
217/// query: Query<(EntityRef, &mut ComponentA)>
218/// # ) {}
219/// # bevy_ecs::system::assert_system_does_not_conflict(system);
220/// ```
221/// ```
222/// # use bevy_ecs::prelude::*;
223/// # #[derive(Component)]
224/// # struct ComponentA;
225/// # #[derive(Component)]
226/// # struct ComponentB;
227/// # fn system(
228/// // This will not panic.
229/// query_a: Query<EntityRef, With<ComponentA>>,
230/// query_b: Query<&mut ComponentB, Without<ComponentA>>,
231/// # ) {}
232/// # bevy_ecs::system::assert_system_does_not_conflict(system);
233/// ```
234///
235/// # Accessing query items
236///
237/// The following table summarizes the behavior of the safe methods that can be used to get query items.
238///
239/// |Query methods|Effect|
240/// |:---:|---|
241/// |[`iter`]\[[`_mut`][`iter_mut`]]|Returns an iterator over all query items.|
242/// |[[`iter().for_each()`][`for_each`]\[[`iter_mut().for_each()`][`for_each`]],<br>[`par_iter`]\[[`_mut`][`par_iter_mut`]]|Runs a specified function for each query item.|
243/// |[`iter_many`]\[[`_mut`][`iter_many_mut`]]|Iterates or runs a specified function over query items generated by a list of entities.|
244/// |[`iter_combinations`]\[[`_mut`][`iter_combinations_mut`]]|Returns an iterator over all combinations of a specified number of query items.|
245/// |[`get`]\[[`_mut`][`get_mut`]]|Returns the query item for the specified entity.|
246/// |[`many`]\[[`_mut`][`many_mut`]],<br>[`get_many`]\[[`_mut`][`get_many_mut`]]|Returns the query items for the specified entities.|
247/// |[`single`]\[[`_mut`][`single_mut`]],<br>[`get_single`]\[[`_mut`][`get_single_mut`]]|Returns the query item while verifying that there aren't others.|
248///
249/// There are two methods for each type of query operation: immutable and mutable (ending with `_mut`).
250/// When using immutable methods, the query items returned are of type [`ROQueryItem`], a read-only version of the query item.
251/// In this circumstance, every mutable reference in the query fetch type parameter is substituted by a shared reference.
252///
253/// # Performance
254///
255/// Creating a `Query` is a low-cost constant operation.
256/// Iterating it, on the other hand, fetches data from the world and generates items, which can have a significant computational cost.
257///
258/// [`Table`] component storage type is much more optimized for query iteration than [`SparseSet`].
259///
260/// Two systems cannot be executed in parallel if both access the same component type where at least one of the accesses is mutable.
261/// This happens unless the executor can verify that no entity could be found in both queries.
262///
263/// Optional components increase the number of entities a query has to match against.
264/// This can hurt iteration performance, especially if the query solely consists of only optional components, since the query would iterate over each entity in the world.
265///
266/// The following table compares the computational complexity of the various methods and operations, where:
267///
268/// - **n** is the number of entities that match the query,
269/// - **r** is the number of elements in a combination,
270/// - **k** is the number of involved entities in the operation,
271/// - **a** is the number of archetypes in the world,
272/// - **C** is the [binomial coefficient], used to count combinations.
273/// <sub>n</sub>C<sub>r</sub> is read as "*n* choose *r*" and is equivalent to the number of distinct unordered subsets of *r* elements that can be taken from a set of *n* elements.
274///
275/// |Query operation|Computational complexity|
276/// |:---:|:---:|
277/// |[`iter`]\[[`_mut`][`iter_mut`]]|O(n)|
278/// |[[`iter().for_each()`][`for_each`]\[[`iter_mut().for_each()`][`for_each`]],<br>[`par_iter`]\[[`_mut`][`par_iter_mut`]]|O(n)|
279/// |[`iter_many`]\[[`_mut`][`iter_many_mut`]]|O(k)|
280/// |[`iter_combinations`]\[[`_mut`][`iter_combinations_mut`]]|O(<sub>n</sub>C<sub>r</sub>)|
281/// |[`get`]\[[`_mut`][`get_mut`]]|O(1)|
282/// |([`get_`][`get_many`])[`many`]|O(k)|
283/// |([`get_`][`get_many_mut`])[`many_mut`]|O(k<sup>2</sup>)|
284/// |[`single`]\[[`_mut`][`single_mut`]],<br>[`get_single`]\[[`_mut`][`get_single_mut`]]|O(a)|
285/// |Archetype based filtering ([`With`], [`Without`], [`Or`])|O(a)|
286/// |Change detection filtering ([`Added`], [`Changed`])|O(a + n)|
287///
288/// # `Iterator::for_each`
289///
290/// `for_each` methods are seen to be generally faster than directly iterating through `iter` on worlds with high archetype
291/// fragmentation, and may enable additional optimizations like [autovectorization]. It is strongly advised to only use
292/// [`Iterator::for_each`] if it tangibly improves performance. *Always* be sure profile or benchmark both before and
293/// after the change!
294///
295/// ```rust
296/// # use bevy_ecs::prelude::*;
297/// # #[derive(Component)]
298/// # struct ComponentA;
299/// # fn system(
300/// # query: Query<&ComponentA>,
301/// # ) {
302/// // This might be result in better performance...
303/// query.iter().for_each(|component| {
304/// // do things with the component
305/// });
306/// // ...than this. Always be sure to benchmark to validate the difference!
307/// for component in query.iter() {
308/// // do things with the component
309/// }
310/// # }
311/// # bevy_ecs::system::assert_system_does_not_conflict(system);
312/// ```
313///
314/// [`Component`]: crate::component::Component
315/// [autovectorization]: https://en.wikipedia.org/wiki/Automatic_vectorization
316/// [`Added`]: crate::query::Added
317/// [`AnyOf`]: crate::query::AnyOf
318/// [binomial coefficient]: https://en.wikipedia.org/wiki/Binomial_coefficient
319/// [`Changed`]: crate::query::Changed
320/// [components]: crate::component::Component
321/// [entity identifiers]: Entity
322/// [`EntityRef`]: crate::world::EntityRef
323/// [`for_each`]: #iterator-for-each
324/// [`get`]: Self::get
325/// [`get_many`]: Self::get_many
326/// [`get_many_mut`]: Self::get_many_mut
327/// [`get_mut`]: Self::get_mut
328/// [`get_single`]: Self::get_single
329/// [`get_single_mut`]: Self::get_single_mut
330/// [`iter`]: Self::iter
331/// [`iter_combinations`]: Self::iter_combinations
332/// [`iter_combinations_mut`]: Self::iter_combinations_mut
333/// [`iter_many`]: Self::iter_many
334/// [`iter_many_mut`]: Self::iter_many_mut
335/// [`iter_mut`]: Self::iter_mut
336/// [`many`]: Self::many
337/// [`many_mut`]: Self::many_mut
338/// [`Or`]: crate::query::Or
339/// [`par_iter`]: Self::par_iter
340/// [`par_iter_mut`]: Self::par_iter_mut
341/// [performance]: #performance
342/// [`single`]: Self::single
343/// [`single_mut`]: Self::single_mut
344/// [`SparseSet`]: crate::storage::SparseSet
345/// [System parameter]: crate::system::SystemParam
346/// [`Table`]: crate::storage::Table
347/// [`With`]: crate::query::With
348/// [`Without`]: crate::query::Without
349pub struct Query<'world, 'state, D: QueryData, F: QueryFilter = ()> {
350 // SAFETY: Must have access to the components registered in `state`.
351 world: UnsafeWorldCell<'world>,
352 state: &'state QueryState<D, F>,
353 last_run: Tick,
354 this_run: Tick,
355}
356
357impl<D: QueryData, F: QueryFilter> std::fmt::Debug for Query<'_, '_, D, F> {
358 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
359 f.debug_struct("Query")
360 .field("matched_entities", &self.iter().count())
361 .field("state", &self.state)
362 .field("last_run", &self.last_run)
363 .field("this_run", &self.this_run)
364 .field("world", &self.world)
365 .finish()
366 }
367}
368
369impl<'w, 's, D: QueryData, F: QueryFilter> Query<'w, 's, D, F> {
370 /// Creates a new query.
371 ///
372 /// # Panics
373 ///
374 /// This will panic if the world used to create `state` is not `world`.
375 ///
376 /// # Safety
377 ///
378 /// This will create a query that could violate memory safety rules. Make sure that this is only
379 /// called in ways that ensure the queries have unique mutable access.
380 #[inline]
381 pub(crate) unsafe fn new(
382 world: UnsafeWorldCell<'w>,
383 state: &'s QueryState<D, F>,
384 last_run: Tick,
385 this_run: Tick,
386 ) -> Self {
387 state.validate_world(world.id());
388
389 Self {
390 world,
391 state,
392 last_run,
393 this_run,
394 }
395 }
396
397 /// Returns another `Query` from this that fetches the read-only version of the query items.
398 ///
399 /// For example, `Query<(&mut D1, &D2, &mut D3), With<F>>` will become `Query<(&D1, &D2, &D3), With<F>>`.
400 /// This can be useful when working around the borrow checker,
401 /// or reusing functionality between systems via functions that accept query types.
402 pub fn to_readonly(&self) -> Query<'_, 's, D::ReadOnly, F> {
403 let new_state = self.state.as_readonly();
404 // SAFETY: This is memory safe because it turns the query immutable.
405 unsafe { Query::new(self.world, new_state, self.last_run, self.this_run) }
406 }
407
408 /// Returns an [`Iterator`] over the read-only query items.
409 ///
410 /// This iterator is always guaranteed to return results from each matching entity once and only once.
411 /// Iteration order is not guaranteed.
412 ///
413 /// # Example
414 ///
415 /// Here, the `report_names_system` iterates over the `Player` component of every entity that contains it:
416 ///
417 /// ```
418 /// # use bevy_ecs::prelude::*;
419 /// #
420 /// # #[derive(Component)]
421 /// # struct Player { name: String }
422 /// #
423 /// fn report_names_system(query: Query<&Player>) {
424 /// for player in &query {
425 /// println!("Say hello to {}!", player.name);
426 /// }
427 /// }
428 /// # bevy_ecs::system::assert_is_system(report_names_system);
429 /// ```
430 ///
431 /// # See also
432 ///
433 /// [`iter_mut`](Self::iter_mut) for mutable query items.
434 #[inline]
435 pub fn iter(&self) -> QueryIter<'_, 's, D::ReadOnly, F> {
436 // SAFETY:
437 // - `self.world` has permission to access the required components.
438 // - The query is read-only, so it can be aliased even if it was originally mutable.
439 unsafe {
440 self.state
441 .as_readonly()
442 .iter_unchecked_manual(self.world, self.last_run, self.this_run)
443 }
444 }
445
446 /// Returns an [`Iterator`] over the query items.
447 ///
448 /// This iterator is always guaranteed to return results from each matching entity once and only once.
449 /// Iteration order is not guaranteed.
450 ///
451 /// # Example
452 ///
453 /// Here, the `gravity_system` updates the `Velocity` component of every entity that contains it:
454 ///
455 /// ```
456 /// # use bevy_ecs::prelude::*;
457 /// #
458 /// # #[derive(Component)]
459 /// # struct Velocity { x: f32, y: f32, z: f32 }
460 /// fn gravity_system(mut query: Query<&mut Velocity>) {
461 /// const DELTA: f32 = 1.0 / 60.0;
462 /// for mut velocity in &mut query {
463 /// velocity.y -= 9.8 * DELTA;
464 /// }
465 /// }
466 /// # bevy_ecs::system::assert_is_system(gravity_system);
467 /// ```
468 ///
469 /// # See also
470 ///
471 /// [`iter`](Self::iter) for read-only query items.
472 #[inline]
473 pub fn iter_mut(&mut self) -> QueryIter<'_, 's, D, F> {
474 // SAFETY: `self.world` has permission to access the required components.
475 unsafe {
476 self.state
477 .iter_unchecked_manual(self.world, self.last_run, self.this_run)
478 }
479 }
480
481 /// Returns a [`QueryCombinationIter`] over all combinations of `K` read-only query items without repetition.
482 ///
483 /// This iterator is always guaranteed to return results from each unique pair of matching entities.
484 /// Iteration order is not guaranteed.
485 ///
486 /// # Example
487 ///
488 /// ```
489 /// # use bevy_ecs::prelude::*;
490 /// # #[derive(Component)]
491 /// # struct ComponentA;
492 /// #
493 /// fn some_system(query: Query<&ComponentA>) {
494 /// for [a1, a2] in query.iter_combinations() {
495 /// // ...
496 /// }
497 /// }
498 /// ```
499 ///
500 /// # See also
501 ///
502 /// - [`iter_combinations_mut`](Self::iter_combinations_mut) for mutable query item combinations.
503 #[inline]
504 pub fn iter_combinations<const K: usize>(
505 &self,
506 ) -> QueryCombinationIter<'_, 's, D::ReadOnly, F, K> {
507 // SAFETY:
508 // - `self.world` has permission to access the required components.
509 // - The query is read-only, so it can be aliased even if it was originally mutable.
510 unsafe {
511 self.state.as_readonly().iter_combinations_unchecked_manual(
512 self.world,
513 self.last_run,
514 self.this_run,
515 )
516 }
517 }
518
519 /// Returns a [`QueryCombinationIter`] over all combinations of `K` query items without repetition.
520 ///
521 /// This iterator is always guaranteed to return results from each unique pair of matching entities.
522 /// Iteration order is not guaranteed.
523 ///
524 /// # Example
525 ///
526 /// ```
527 /// # use bevy_ecs::prelude::*;
528 /// # #[derive(Component)]
529 /// # struct ComponentA;
530 /// fn some_system(mut query: Query<&mut ComponentA>) {
531 /// let mut combinations = query.iter_combinations_mut();
532 /// while let Some([mut a1, mut a2]) = combinations.fetch_next() {
533 /// // mutably access components data
534 /// }
535 /// }
536 /// ```
537 ///
538 /// # See also
539 ///
540 /// - [`iter_combinations`](Self::iter_combinations) for read-only query item combinations.
541 #[inline]
542 pub fn iter_combinations_mut<const K: usize>(
543 &mut self,
544 ) -> QueryCombinationIter<'_, 's, D, F, K> {
545 // SAFETY: `self.world` has permission to access the required components.
546 unsafe {
547 self.state
548 .iter_combinations_unchecked_manual(self.world, self.last_run, self.this_run)
549 }
550 }
551
552 /// Returns an [`Iterator`] over the read-only query items generated from an [`Entity`] list.
553 ///
554 /// Items are returned in the order of the list of entities, and may not be unique if the input
555 /// doesn't guarantee uniqueness. Entities that don't match the query are skipped.
556 ///
557 /// # Example
558 ///
559 /// ```
560 /// # use bevy_ecs::prelude::*;
561 /// # #[derive(Component)]
562 /// # struct Counter {
563 /// # value: i32
564 /// # }
565 /// #
566 /// // A component containing an entity list.
567 /// #[derive(Component)]
568 /// struct Friends {
569 /// list: Vec<Entity>,
570 /// }
571 ///
572 /// fn system(
573 /// friends_query: Query<&Friends>,
574 /// counter_query: Query<&Counter>,
575 /// ) {
576 /// for friends in &friends_query {
577 /// for counter in counter_query.iter_many(&friends.list) {
578 /// println!("Friend's counter: {:?}", counter.value);
579 /// }
580 /// }
581 /// }
582 /// # bevy_ecs::system::assert_is_system(system);
583 /// ```
584 ///
585 /// # See also
586 ///
587 /// - [`iter_many_mut`](Self::iter_many_mut) to get mutable query items.
588 #[inline]
589 pub fn iter_many<EntityList: IntoIterator>(
590 &self,
591 entities: EntityList,
592 ) -> QueryManyIter<'_, 's, D::ReadOnly, F, EntityList::IntoIter>
593 where
594 EntityList::Item: Borrow<Entity>,
595 {
596 // SAFETY:
597 // - `self.world` has permission to access the required components.
598 // - The query is read-only, so it can be aliased even if it was originally mutable.
599 unsafe {
600 self.state.as_readonly().iter_many_unchecked_manual(
601 entities,
602 self.world,
603 self.last_run,
604 self.this_run,
605 )
606 }
607 }
608
609 /// Returns an iterator over the query items generated from an [`Entity`] list.
610 ///
611 /// Items are returned in the order of the list of entities, and may not be unique if the input
612 /// doesnn't guarantee uniqueness. Entities that don't match the query are skipped.
613 ///
614 /// # Examples
615 ///
616 /// ```
617 /// # use bevy_ecs::prelude::*;
618 /// #[derive(Component)]
619 /// struct Counter {
620 /// value: i32
621 /// }
622 ///
623 /// #[derive(Component)]
624 /// struct Friends {
625 /// list: Vec<Entity>,
626 /// }
627 ///
628 /// fn system(
629 /// friends_query: Query<&Friends>,
630 /// mut counter_query: Query<&mut Counter>,
631 /// ) {
632 /// for friends in &friends_query {
633 /// let mut iter = counter_query.iter_many_mut(&friends.list);
634 /// while let Some(mut counter) = iter.fetch_next() {
635 /// println!("Friend's counter: {:?}", counter.value);
636 /// counter.value += 1;
637 /// }
638 /// }
639 /// }
640 /// # bevy_ecs::system::assert_is_system(system);
641 /// ```
642 #[inline]
643 pub fn iter_many_mut<EntityList: IntoIterator>(
644 &mut self,
645 entities: EntityList,
646 ) -> QueryManyIter<'_, 's, D, F, EntityList::IntoIter>
647 where
648 EntityList::Item: Borrow<Entity>,
649 {
650 // SAFETY: `self.world` has permission to access the required components.
651 unsafe {
652 self.state.iter_many_unchecked_manual(
653 entities,
654 self.world,
655 self.last_run,
656 self.this_run,
657 )
658 }
659 }
660
661 /// Returns an [`Iterator`] over the query items.
662 ///
663 /// This iterator is always guaranteed to return results from each matching entity once and only once.
664 /// Iteration order is not guaranteed.
665 ///
666 /// # Safety
667 ///
668 /// This function makes it possible to violate Rust's aliasing guarantees.
669 /// You must make sure this call does not result in multiple mutable references to the same component.
670 ///
671 /// # See also
672 ///
673 /// - [`iter`](Self::iter) and [`iter_mut`](Self::iter_mut) for the safe versions.
674 #[inline]
675 pub unsafe fn iter_unsafe(&self) -> QueryIter<'_, 's, D, F> {
676 // SAFETY:
677 // - `self.world` has permission to access the required components.
678 // - The caller ensures that this operation will not result in any aliased mutable accesses.
679 unsafe {
680 self.state
681 .iter_unchecked_manual(self.world, self.last_run, self.this_run)
682 }
683 }
684
685 /// Iterates over all possible combinations of `K` query items without repetition.
686 ///
687 /// This iterator is always guaranteed to return results from each unique pair of matching entities.
688 /// Iteration order is not guaranteed.
689 ///
690 /// # Safety
691 ///
692 /// This allows aliased mutability.
693 /// You must make sure this call does not result in multiple mutable references to the same component.
694 ///
695 /// # See also
696 ///
697 /// - [`iter_combinations`](Self::iter_combinations) and [`iter_combinations_mut`](Self::iter_combinations_mut) for the safe versions.
698 #[inline]
699 pub unsafe fn iter_combinations_unsafe<const K: usize>(
700 &self,
701 ) -> QueryCombinationIter<'_, 's, D, F, K> {
702 // SAFETY:
703 // - `self.world` has permission to access the required components.
704 // - The caller ensures that this operation will not result in any aliased mutable accesses.
705 unsafe {
706 self.state
707 .iter_combinations_unchecked_manual(self.world, self.last_run, self.this_run)
708 }
709 }
710
711 /// Returns an [`Iterator`] over the query items generated from an [`Entity`] list.
712 ///
713 /// Items are returned in the order of the list of entities, and may not be unique if the input
714 /// doesnn't guarantee uniqueness. Entities that don't match the query are skipped.
715 ///
716 /// # Safety
717 ///
718 /// This allows aliased mutability and does not check for entity uniqueness.
719 /// You must make sure this call does not result in multiple mutable references to the same component.
720 /// Particular care must be taken when collecting the data (rather than iterating over it one item at a time) such as via [`Iterator::collect`].
721 ///
722 /// # See also
723 ///
724 /// - [`iter_many_mut`](Self::iter_many_mut) to safely access the query items.
725 pub unsafe fn iter_many_unsafe<EntityList: IntoIterator>(
726 &self,
727 entities: EntityList,
728 ) -> QueryManyIter<'_, 's, D, F, EntityList::IntoIter>
729 where
730 EntityList::Item: Borrow<Entity>,
731 {
732 // SAFETY:
733 // - `self.world` has permission to access the required components.
734 // - The caller ensures that this operation will not result in any aliased mutable accesses.
735 unsafe {
736 self.state.iter_many_unchecked_manual(
737 entities,
738 self.world,
739 self.last_run,
740 self.this_run,
741 )
742 }
743 }
744
745 /// Returns a parallel iterator over the query results for the given [`World`].
746 ///
747 /// This parallel iterator is always guaranteed to return results from each matching entity once and
748 /// only once. Iteration order and thread assignment is not guaranteed.
749 ///
750 /// If the `multithreaded` feature is disabled, iterating with this operates identically to [`Iterator::for_each`]
751 /// on [`QueryIter`].
752 ///
753 /// This can only be called for read-only queries, see [`par_iter_mut`] for write-queries.
754 ///
755 /// Note that you must use the `for_each` method to iterate over the
756 /// results, see [`par_iter_mut`] for an example.
757 ///
758 /// [`par_iter_mut`]: Self::par_iter_mut
759 /// [`World`]: crate::world::World
760 #[inline]
761 pub fn par_iter(&self) -> QueryParIter<'_, '_, D::ReadOnly, F> {
762 QueryParIter {
763 world: self.world,
764 state: self.state.as_readonly(),
765 last_run: self.last_run,
766 this_run: self.this_run,
767 batching_strategy: BatchingStrategy::new(),
768 }
769 }
770
771 /// Returns a parallel iterator over the query results for the given [`World`].
772 ///
773 /// This parallel iterator is always guaranteed to return results from each matching entity once and
774 /// only once. Iteration order and thread assignment is not guaranteed.
775 ///
776 /// If the `multithreaded` feature is disabled, iterating with this operates identically to [`Iterator::for_each`]
777 /// on [`QueryIter`].
778 ///
779 /// This can only be called for mutable queries, see [`par_iter`] for read-only-queries.
780 ///
781 /// # Example
782 ///
783 /// Here, the `gravity_system` updates the `Velocity` component of every entity that contains it:
784 ///
785 /// ```
786 /// # use bevy_ecs::prelude::*;
787 /// #
788 /// # #[derive(Component)]
789 /// # struct Velocity { x: f32, y: f32, z: f32 }
790 /// fn gravity_system(mut query: Query<&mut Velocity>) {
791 /// const DELTA: f32 = 1.0 / 60.0;
792 /// query.par_iter_mut().for_each(|mut velocity| {
793 /// velocity.y -= 9.8 * DELTA;
794 /// });
795 /// }
796 /// # bevy_ecs::system::assert_is_system(gravity_system);
797 /// ```
798 ///
799 /// [`par_iter`]: Self::par_iter
800 /// [`World`]: crate::world::World
801 #[inline]
802 pub fn par_iter_mut(&mut self) -> QueryParIter<'_, '_, D, F> {
803 QueryParIter {
804 world: self.world,
805 state: self.state,
806 last_run: self.last_run,
807 this_run: self.this_run,
808 batching_strategy: BatchingStrategy::new(),
809 }
810 }
811
812 /// Returns the read-only query item for the given [`Entity`].
813 ///
814 /// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.
815 ///
816 /// This is always guaranteed to run in `O(1)` time.
817 ///
818 /// # Example
819 ///
820 /// Here, `get` is used to retrieve the exact query item of the entity specified by the `SelectedCharacter` resource.
821 ///
822 /// ```
823 /// # use bevy_ecs::prelude::*;
824 /// #
825 /// # #[derive(Resource)]
826 /// # struct SelectedCharacter { entity: Entity }
827 /// # #[derive(Component)]
828 /// # struct Character { name: String }
829 /// #
830 /// fn print_selected_character_name_system(
831 /// query: Query<&Character>,
832 /// selection: Res<SelectedCharacter>
833 /// )
834 /// {
835 /// if let Ok(selected_character) = query.get(selection.entity) {
836 /// println!("{}", selected_character.name);
837 /// }
838 /// }
839 /// # bevy_ecs::system::assert_is_system(print_selected_character_name_system);
840 /// ```
841 ///
842 /// # See also
843 ///
844 /// - [`get_mut`](Self::get_mut) to get a mutable query item.
845 #[inline]
846 pub fn get(&self, entity: Entity) -> Result<ROQueryItem<'_, D>, QueryEntityError> {
847 // SAFETY: system runs without conflicts with other systems.
848 // same-system queries have runtime borrow checks when they conflict
849 unsafe {
850 self.state.as_readonly().get_unchecked_manual(
851 self.world,
852 entity,
853 self.last_run,
854 self.this_run,
855 )
856 }
857 }
858
859 /// Returns the read-only query items for the given array of [`Entity`].
860 ///
861 /// The returned query items are in the same order as the input.
862 /// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.
863 /// The elements of the array do not need to be unique, unlike `get_many_mut`.
864 ///
865 /// # See also
866 ///
867 /// - [`get_many_mut`](Self::get_many_mut) to get mutable query items.
868 /// - [`many`](Self::many) for the panicking version.
869 #[inline]
870 pub fn get_many<const N: usize>(
871 &self,
872 entities: [Entity; N],
873 ) -> Result<[ROQueryItem<'_, D>; N], QueryEntityError> {
874 // SAFETY:
875 // - `&self` ensures there is no mutable access to any components accessible to this query.
876 // - `self.world` matches `self.state`.
877 unsafe {
878 self.state
879 .get_many_read_only_manual(self.world, entities, self.last_run, self.this_run)
880 }
881 }
882
883 /// Returns the read-only query items for the given array of [`Entity`].
884 ///
885 /// # Panics
886 ///
887 /// This method panics if there is a query mismatch or a non-existing entity.
888 ///
889 /// # Examples
890 /// ``` no_run
891 /// use bevy_ecs::prelude::*;
892 ///
893 /// #[derive(Component)]
894 /// struct Targets([Entity; 3]);
895 ///
896 /// #[derive(Component)]
897 /// struct Position{
898 /// x: i8,
899 /// y: i8
900 /// };
901 ///
902 /// impl Position {
903 /// fn distance(&self, other: &Position) -> i8 {
904 /// // Manhattan distance is way easier to compute!
905 /// (self.x - other.x).abs() + (self.y - other.y).abs()
906 /// }
907 /// }
908 ///
909 /// fn check_all_targets_in_range(targeting_query: Query<(Entity, &Targets, &Position)>, targets_query: Query<&Position>){
910 /// for (targeting_entity, targets, origin) in &targeting_query {
911 /// // We can use "destructuring" to unpack the results nicely
912 /// let [target_1, target_2, target_3] = targets_query.many(targets.0);
913 ///
914 /// assert!(target_1.distance(origin) <= 5);
915 /// assert!(target_2.distance(origin) <= 5);
916 /// assert!(target_3.distance(origin) <= 5);
917 /// }
918 /// }
919 /// ```
920 ///
921 /// # See also
922 ///
923 /// - [`get_many`](Self::get_many) for the non-panicking version.
924 #[inline]
925 #[track_caller]
926 pub fn many<const N: usize>(&self, entities: [Entity; N]) -> [ROQueryItem<'_, D>; N] {
927 match self.get_many(entities) {
928 Ok(items) => items,
929 Err(error) => panic!("Cannot get query results: {error}"),
930 }
931 }
932
933 /// Returns the query item for the given [`Entity`].
934 ///
935 /// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.
936 ///
937 /// This is always guaranteed to run in `O(1)` time.
938 ///
939 /// # Example
940 ///
941 /// Here, `get_mut` is used to retrieve the exact query item of the entity specified by the `PoisonedCharacter` resource.
942 ///
943 /// ```
944 /// # use bevy_ecs::prelude::*;
945 /// #
946 /// # #[derive(Resource)]
947 /// # struct PoisonedCharacter { character_id: Entity }
948 /// # #[derive(Component)]
949 /// # struct Health(u32);
950 /// #
951 /// fn poison_system(mut query: Query<&mut Health>, poisoned: Res<PoisonedCharacter>) {
952 /// if let Ok(mut health) = query.get_mut(poisoned.character_id) {
953 /// health.0 -= 1;
954 /// }
955 /// }
956 /// # bevy_ecs::system::assert_is_system(poison_system);
957 /// ```
958 ///
959 /// # See also
960 ///
961 /// - [`get`](Self::get) to get a read-only query item.
962 #[inline]
963 pub fn get_mut(&mut self, entity: Entity) -> Result<D::Item<'_>, QueryEntityError> {
964 // SAFETY: system runs without conflicts with other systems.
965 // same-system queries have runtime borrow checks when they conflict
966 unsafe {
967 self.state
968 .get_unchecked_manual(self.world, entity, self.last_run, self.this_run)
969 }
970 }
971
972 /// Returns the query items for the given array of [`Entity`].
973 ///
974 /// The returned query items are in the same order as the input.
975 /// In case of a nonexisting entity, duplicate entities or mismatched component, a [`QueryEntityError`] is returned instead.
976 ///
977 /// # See also
978 ///
979 /// - [`get_many`](Self::get_many) to get read-only query items.
980 /// - [`many_mut`](Self::many_mut) for the panicking version.
981 #[inline]
982 pub fn get_many_mut<const N: usize>(
983 &mut self,
984 entities: [Entity; N],
985 ) -> Result<[D::Item<'_>; N], QueryEntityError> {
986 // SAFETY: scheduler ensures safe Query world access
987 unsafe {
988 self.state
989 .get_many_unchecked_manual(self.world, entities, self.last_run, self.this_run)
990 }
991 }
992
993 /// Returns the query items for the given array of [`Entity`].
994 ///
995 /// # Panics
996 ///
997 /// This method panics if there is a query mismatch, a non-existing entity, or the same `Entity` is included more than once in the array.
998 ///
999 /// # Examples
1000 ///
1001 /// ``` no_run
1002 /// use bevy_ecs::prelude::*;
1003 ///
1004 /// #[derive(Component)]
1005 /// struct Spring{
1006 /// connected_entities: [Entity; 2],
1007 /// strength: f32,
1008 /// }
1009 ///
1010 /// #[derive(Component)]
1011 /// struct Position {
1012 /// x: f32,
1013 /// y: f32,
1014 /// }
1015 ///
1016 /// #[derive(Component)]
1017 /// struct Force {
1018 /// x: f32,
1019 /// y: f32,
1020 /// }
1021 ///
1022 /// fn spring_forces(spring_query: Query<&Spring>, mut mass_query: Query<(&Position, &mut Force)>){
1023 /// for spring in &spring_query {
1024 /// // We can use "destructuring" to unpack our query items nicely
1025 /// let [(position_1, mut force_1), (position_2, mut force_2)] = mass_query.many_mut(spring.connected_entities);
1026 ///
1027 /// force_1.x += spring.strength * (position_1.x - position_2.x);
1028 /// force_1.y += spring.strength * (position_1.y - position_2.y);
1029 ///
1030 /// // Silence borrow-checker: I have split your mutable borrow!
1031 /// force_2.x += spring.strength * (position_2.x - position_1.x);
1032 /// force_2.y += spring.strength * (position_2.y - position_1.y);
1033 /// }
1034 /// }
1035 /// ```
1036 ///
1037 /// # See also
1038 ///
1039 /// - [`get_many_mut`](Self::get_many_mut) for the non panicking version.
1040 /// - [`many`](Self::many) to get read-only query items.
1041 #[inline]
1042 #[track_caller]
1043 pub fn many_mut<const N: usize>(&mut self, entities: [Entity; N]) -> [D::Item<'_>; N] {
1044 match self.get_many_mut(entities) {
1045 Ok(items) => items,
1046 Err(error) => panic!("Cannot get query result: {error}"),
1047 }
1048 }
1049
1050 /// Returns the query item for the given [`Entity`].
1051 ///
1052 /// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is returned instead.
1053 ///
1054 /// This is always guaranteed to run in `O(1)` time.
1055 ///
1056 /// # Safety
1057 ///
1058 /// This function makes it possible to violate Rust's aliasing guarantees.
1059 /// You must make sure this call does not result in multiple mutable references to the same component.
1060 ///
1061 /// # See also
1062 ///
1063 /// - [`get_mut`](Self::get_mut) for the safe version.
1064 #[inline]
1065 pub unsafe fn get_unchecked(&self, entity: Entity) -> Result<D::Item<'_>, QueryEntityError> {
1066 // SEMI-SAFETY: system runs without conflicts with other systems.
1067 // same-system queries have runtime borrow checks when they conflict
1068 unsafe {
1069 self.state
1070 .get_unchecked_manual(self.world, entity, self.last_run, self.this_run)
1071 }
1072 }
1073
1074 /// Returns a single read-only query item when there is exactly one entity matching the query.
1075 ///
1076 /// # Panics
1077 ///
1078 /// This method panics if the number of query items is **not** exactly one.
1079 ///
1080 /// # Example
1081 ///
1082 /// ```
1083 /// # use bevy_ecs::prelude::*;
1084 /// # #[derive(Component)]
1085 /// # struct Player;
1086 /// # #[derive(Component)]
1087 /// # struct Position(f32, f32);
1088 /// fn player_system(query: Query<&Position, With<Player>>) {
1089 /// let player_position = query.single();
1090 /// // do something with player_position
1091 /// }
1092 /// # bevy_ecs::system::assert_is_system(player_system);
1093 /// ```
1094 ///
1095 /// # See also
1096 ///
1097 /// - [`get_single`](Self::get_single) for the non-panicking version.
1098 /// - [`single_mut`](Self::single_mut) to get the mutable query item.
1099 #[track_caller]
1100 pub fn single(&self) -> ROQueryItem<'_, D> {
1101 self.get_single().unwrap()
1102 }
1103
1104 /// Returns a single read-only query item when there is exactly one entity matching the query.
1105 ///
1106 /// If the number of query items is not exactly one, a [`QuerySingleError`] is returned instead.
1107 ///
1108 /// # Example
1109 ///
1110 /// ```
1111 /// # use bevy_ecs::prelude::*;
1112 /// # use bevy_ecs::query::QuerySingleError;
1113 /// # #[derive(Component)]
1114 /// # struct PlayerScore(i32);
1115 /// fn player_scoring_system(query: Query<&PlayerScore>) {
1116 /// match query.get_single() {
1117 /// Ok(PlayerScore(score)) => {
1118 /// println!("Score: {}", score);
1119 /// }
1120 /// Err(QuerySingleError::NoEntities(_)) => {
1121 /// println!("Error: There is no player!");
1122 /// }
1123 /// Err(QuerySingleError::MultipleEntities(_)) => {
1124 /// println!("Error: There is more than one player!");
1125 /// }
1126 /// }
1127 /// }
1128 /// # bevy_ecs::system::assert_is_system(player_scoring_system);
1129 /// ```
1130 ///
1131 /// # See also
1132 ///
1133 /// - [`get_single_mut`](Self::get_single_mut) to get the mutable query item.
1134 /// - [`single`](Self::single) for the panicking version.
1135 #[inline]
1136 pub fn get_single(&self) -> Result<ROQueryItem<'_, D>, QuerySingleError> {
1137 // SAFETY:
1138 // the query ensures that the components it accesses are not mutably accessible somewhere else
1139 // and the query is read only.
1140 unsafe {
1141 self.state.as_readonly().get_single_unchecked_manual(
1142 self.world,
1143 self.last_run,
1144 self.this_run,
1145 )
1146 }
1147 }
1148
1149 /// Returns a single query item when there is exactly one entity matching the query.
1150 ///
1151 /// # Panics
1152 ///
1153 /// This method panics if the number of query item is **not** exactly one.
1154 ///
1155 /// # Example
1156 ///
1157 /// ```
1158 /// # use bevy_ecs::prelude::*;
1159 /// #
1160 /// # #[derive(Component)]
1161 /// # struct Player;
1162 /// # #[derive(Component)]
1163 /// # struct Health(u32);
1164 /// #
1165 /// fn regenerate_player_health_system(mut query: Query<&mut Health, With<Player>>) {
1166 /// let mut health = query.single_mut();
1167 /// health.0 += 1;
1168 /// }
1169 /// # bevy_ecs::system::assert_is_system(regenerate_player_health_system);
1170 /// ```
1171 ///
1172 /// # See also
1173 ///
1174 /// - [`get_single_mut`](Self::get_single_mut) for the non-panicking version.
1175 /// - [`single`](Self::single) to get the read-only query item.
1176 #[track_caller]
1177 pub fn single_mut(&mut self) -> D::Item<'_> {
1178 self.get_single_mut().unwrap()
1179 }
1180
1181 /// Returns a single query item when there is exactly one entity matching the query.
1182 ///
1183 /// If the number of query items is not exactly one, a [`QuerySingleError`] is returned instead.
1184 ///
1185 /// # Example
1186 ///
1187 /// ```
1188 /// # use bevy_ecs::prelude::*;
1189 /// #
1190 /// # #[derive(Component)]
1191 /// # struct Player;
1192 /// # #[derive(Component)]
1193 /// # struct Health(u32);
1194 /// #
1195 /// fn regenerate_player_health_system(mut query: Query<&mut Health, With<Player>>) {
1196 /// let mut health = query.get_single_mut().expect("Error: Could not find a single player.");
1197 /// health.0 += 1;
1198 /// }
1199 /// # bevy_ecs::system::assert_is_system(regenerate_player_health_system);
1200 /// ```
1201 ///
1202 /// # See also
1203 ///
1204 /// - [`get_single`](Self::get_single) to get the read-only query item.
1205 /// - [`single_mut`](Self::single_mut) for the panicking version.
1206 #[inline]
1207 pub fn get_single_mut(&mut self) -> Result<D::Item<'_>, QuerySingleError> {
1208 // SAFETY:
1209 // the query ensures mutable access to the components it accesses, and the query
1210 // is uniquely borrowed
1211 unsafe {
1212 self.state
1213 .get_single_unchecked_manual(self.world, self.last_run, self.this_run)
1214 }
1215 }
1216
1217 /// Returns `true` if there are no query items.
1218 ///
1219 /// This is equivalent to `self.iter().next().is_none()`, and thus the worst case runtime will be `O(n)`
1220 /// where `n` is the number of *potential* matches. This can be notably expensive for queries that rely
1221 /// on non-archetypal filters such as [`Added`] or [`Changed`] which must individually check each query
1222 /// result for a match.
1223 ///
1224 /// # Example
1225 ///
1226 /// Here, the score is increased only if an entity with a `Player` component is present in the world:
1227 ///
1228 /// ```
1229 /// # use bevy_ecs::prelude::*;
1230 /// #
1231 /// # #[derive(Component)]
1232 /// # struct Player;
1233 /// # #[derive(Resource)]
1234 /// # struct Score(u32);
1235 /// fn update_score_system(query: Query<(), With<Player>>, mut score: ResMut<Score>) {
1236 /// if !query.is_empty() {
1237 /// score.0 += 1;
1238 /// }
1239 /// }
1240 /// # bevy_ecs::system::assert_is_system(update_score_system);
1241 /// ```
1242 ///
1243 /// [`Added`]: crate::query::Added
1244 /// [`Changed`]: crate::query::Changed
1245 #[inline]
1246 pub fn is_empty(&self) -> bool {
1247 // SAFETY:
1248 // - `self.world` has permission to read any data required by the WorldQuery.
1249 // - `&self` ensures that no one currently has write access.
1250 // - `self.world` matches `self.state`.
1251 unsafe {
1252 self.state
1253 .is_empty_unsafe_world_cell(self.world, self.last_run, self.this_run)
1254 }
1255 }
1256
1257 /// Returns `true` if the given [`Entity`] matches the query.
1258 ///
1259 /// This is always guaranteed to run in `O(1)` time.
1260 ///
1261 /// # Example
1262 ///
1263 /// ```
1264 /// # use bevy_ecs::prelude::*;
1265 /// #
1266 /// # #[derive(Component)]
1267 /// # struct InRange;
1268 /// #
1269 /// # #[derive(Resource)]
1270 /// # struct Target {
1271 /// # entity: Entity,
1272 /// # }
1273 /// #
1274 /// fn targeting_system(in_range_query: Query<&InRange>, target: Res<Target>) {
1275 /// if in_range_query.contains(target.entity) {
1276 /// println!("Bam!")
1277 /// }
1278 /// }
1279 /// # bevy_ecs::system::assert_is_system(targeting_system);
1280 /// ```
1281 #[inline]
1282 pub fn contains(&self, entity: Entity) -> bool {
1283 // SAFETY: NopFetch does not access any members while &self ensures no one has exclusive access
1284 unsafe {
1285 self.state
1286 .as_nop()
1287 .get_unchecked_manual(self.world, entity, self.last_run, self.this_run)
1288 .is_ok()
1289 }
1290 }
1291
1292 /// Returns a [`QueryLens`] that can be used to get a query with a more general fetch.
1293 ///
1294 /// For example, this can transform a `Query<(&A, &mut B)>` to a `Query<&B>`.
1295 /// This can be useful for passing the query to another function. Note that since
1296 /// filter terms are dropped, non-archetypal filters like [`Added`](crate::query::Added) and
1297 /// [`Changed`](crate::query::Changed) will not be respected. To maintain or change filter
1298 /// terms see [`Self::transmute_lens_filtered`]
1299 ///
1300 /// ## Panics
1301 ///
1302 /// This will panic if `NewD` is not a subset of the original fetch `Q`
1303 ///
1304 /// ## Example
1305 ///
1306 /// ```rust
1307 /// # use bevy_ecs::prelude::*;
1308 /// # use bevy_ecs::system::QueryLens;
1309 /// #
1310 /// # #[derive(Component)]
1311 /// # struct A(usize);
1312 /// #
1313 /// # #[derive(Component)]
1314 /// # struct B(usize);
1315 /// #
1316 /// # let mut world = World::new();
1317 /// #
1318 /// # world.spawn((A(10), B(5)));
1319 /// #
1320 /// fn reusable_function(lens: &mut QueryLens<&A>) {
1321 /// assert_eq!(lens.query().single().0, 10);
1322 /// }
1323 ///
1324 /// // We can use the function in a system that takes the exact query.
1325 /// fn system_1(mut query: Query<&A>) {
1326 /// reusable_function(&mut query.as_query_lens());
1327 /// }
1328 ///
1329 /// // We can also use it with a query that does not match exactly
1330 /// // by transmuting it.
1331 /// fn system_2(mut query: Query<(&mut A, &B)>) {
1332 /// let mut lens = query.transmute_lens::<&A>();
1333 /// reusable_function(&mut lens);
1334 /// }
1335 ///
1336 /// # let mut schedule = Schedule::default();
1337 /// # schedule.add_systems((system_1, system_2));
1338 /// # schedule.run(&mut world);
1339 /// ```
1340 ///
1341 /// ## Allowed Transmutes
1342 ///
1343 /// Besides removing parameters from the query, you can also
1344 /// make limited changes to the types of parameters.
1345 ///
1346 /// * Can always add/remove [`Entity`]
1347 /// * Can always add/remove [`EntityLocation`]
1348 /// * Can always add/remove [`&Archetype`]
1349 /// * `Ref<T>` <-> `&T`
1350 /// * `&mut T` -> `&T`
1351 /// * `&mut T` -> `Ref<T>`
1352 /// * [`EntityMut`](crate::world::EntityMut) -> [`EntityRef`](crate::world::EntityRef)
1353 ///
1354 /// [`EntityLocation`]: crate::entity::EntityLocation
1355 /// [`&Archetype`]: crate::archetype::Archetype
1356 #[track_caller]
1357 pub fn transmute_lens<NewD: QueryData>(&mut self) -> QueryLens<'_, NewD> {
1358 self.transmute_lens_filtered::<NewD, ()>()
1359 }
1360
1361 /// Equivalent to [`Self::transmute_lens`] but also includes a [`QueryFilter`] type.
1362 ///
1363 /// Note that the lens will iterate the same tables and archetypes as the original query. This means that
1364 /// additional archetypal query terms like [`With`](crate::query::With) and [`Without`](crate::query::Without)
1365 /// will not necessarily be respected and non-archetypal terms like [`Added`](crate::query::Added) and
1366 /// [`Changed`](crate::query::Changed) will only be respected if they are in the type signature.
1367 #[track_caller]
1368 pub fn transmute_lens_filtered<NewD: QueryData, NewF: QueryFilter>(
1369 &mut self,
1370 ) -> QueryLens<'_, NewD, NewF> {
1371 let components = self.world.components();
1372 let state = self.state.transmute_filtered::<NewD, NewF>(components);
1373 QueryLens {
1374 world: self.world,
1375 state,
1376 last_run: self.last_run,
1377 this_run: self.this_run,
1378 }
1379 }
1380
1381 /// Gets a [`QueryLens`] with the same accesses as the existing query
1382 pub fn as_query_lens(&mut self) -> QueryLens<'_, D> {
1383 self.transmute_lens()
1384 }
1385
1386 /// Returns a [`QueryLens`] that can be used to get a query with the combined fetch.
1387 ///
1388 /// For example, this can take a `Query<&A>` and a `Query<&B>` and return a `Query<(&A, &B)>`.
1389 /// The returned query will only return items with both `A` and `B`. Note that since filters
1390 /// are dropped, non-archetypal filters like `Added` and `Changed` will not be respected.
1391 /// To maintain or change filter terms see `Self::join_filtered`.
1392 ///
1393 /// ## Example
1394 ///
1395 /// ```rust
1396 /// # use bevy_ecs::prelude::*;
1397 /// # use bevy_ecs::system::QueryLens;
1398 /// #
1399 /// # #[derive(Component)]
1400 /// # struct Transform;
1401 /// #
1402 /// # #[derive(Component)]
1403 /// # struct Player;
1404 /// #
1405 /// # #[derive(Component)]
1406 /// # struct Enemy;
1407 /// #
1408 /// # let mut world = World::default();
1409 /// # world.spawn((Transform, Player));
1410 /// # world.spawn((Transform, Enemy));
1411 ///
1412 /// fn system(
1413 /// mut transforms: Query<&Transform>,
1414 /// mut players: Query<&Player>,
1415 /// mut enemies: Query<&Enemy>
1416 /// ) {
1417 /// let mut players_transforms: QueryLens<(&Transform, &Player)> = transforms.join(&mut players);
1418 /// for (transform, player) in &players_transforms.query() {
1419 /// // do something with a and b
1420 /// }
1421 ///
1422 /// let mut enemies_transforms: QueryLens<(&Transform, &Enemy)> = transforms.join(&mut enemies);
1423 /// for (transform, enemy) in &enemies_transforms.query() {
1424 /// // do something with a and b
1425 /// }
1426 /// }
1427 ///
1428 /// # let mut schedule = Schedule::default();
1429 /// # schedule.add_systems(system);
1430 /// # schedule.run(&mut world);
1431 /// ```
1432 /// ## Panics
1433 ///
1434 /// This will panic if `NewD` is not a subset of the union of the original fetch `Q` and `OtherD`.
1435 ///
1436 /// ## Allowed Transmutes
1437 ///
1438 /// Like `transmute_lens` the query terms can be changed with some restrictions.
1439 /// See [`Self::transmute_lens`] for more details.
1440 pub fn join<OtherD: QueryData, NewD: QueryData>(
1441 &mut self,
1442 other: &mut Query<OtherD>,
1443 ) -> QueryLens<'_, NewD> {
1444 self.join_filtered(other)
1445 }
1446
1447 /// Equivalent to [`Self::join`] but also includes a [`QueryFilter`] type.
1448 ///
1449 /// Note that the lens with iterate a subset of the original queries' tables
1450 /// and archetypes. This means that additional archetypal query terms like
1451 /// `With` and `Without` will not necessarily be respected and non-archetypal
1452 /// terms like `Added` and `Changed` will only be respected if they are in
1453 /// the type signature.
1454 pub fn join_filtered<
1455 OtherD: QueryData,
1456 OtherF: QueryFilter,
1457 NewD: QueryData,
1458 NewF: QueryFilter,
1459 >(
1460 &mut self,
1461 other: &mut Query<OtherD, OtherF>,
1462 ) -> QueryLens<'_, NewD, NewF> {
1463 let components = self.world.components();
1464 let state = self
1465 .state
1466 .join_filtered::<OtherD, OtherF, NewD, NewF>(components, other.state);
1467 QueryLens {
1468 world: self.world,
1469 state,
1470 last_run: self.last_run,
1471 this_run: self.this_run,
1472 }
1473 }
1474}
1475
1476impl<'w, 's, D: QueryData, F: QueryFilter> IntoIterator for &'w Query<'_, 's, D, F> {
1477 type Item = ROQueryItem<'w, D>;
1478 type IntoIter = QueryIter<'w, 's, D::ReadOnly, F>;
1479
1480 fn into_iter(self) -> Self::IntoIter {
1481 self.iter()
1482 }
1483}
1484
1485impl<'w, 's, D: QueryData, F: QueryFilter> IntoIterator for &'w mut Query<'_, 's, D, F> {
1486 type Item = D::Item<'w>;
1487 type IntoIter = QueryIter<'w, 's, D, F>;
1488
1489 fn into_iter(self) -> Self::IntoIter {
1490 self.iter_mut()
1491 }
1492}
1493
1494impl<'w, 's, D: ReadOnlyQueryData, F: QueryFilter> Query<'w, 's, D, F> {
1495 /// Returns the query item for the given [`Entity`], with the actual "inner" world lifetime.
1496 ///
1497 /// In case of a nonexisting entity or mismatched component, a [`QueryEntityError`] is
1498 /// returned instead.
1499 ///
1500 /// This can only return immutable data (mutable data will be cast to an immutable form).
1501 /// See [`get_mut`](Self::get_mut) for queries that contain at least one mutable component.
1502 ///
1503 /// # Example
1504 ///
1505 /// Here, `get` is used to retrieve the exact query item of the entity specified by the
1506 /// `SelectedCharacter` resource.
1507 ///
1508 /// ```
1509 /// # use bevy_ecs::prelude::*;
1510 /// #
1511 /// # #[derive(Resource)]
1512 /// # struct SelectedCharacter { entity: Entity }
1513 /// # #[derive(Component)]
1514 /// # struct Character { name: String }
1515 /// #
1516 /// fn print_selected_character_name_system(
1517 /// query: Query<&Character>,
1518 /// selection: Res<SelectedCharacter>
1519 /// )
1520 /// {
1521 /// if let Ok(selected_character) = query.get(selection.entity) {
1522 /// println!("{}", selected_character.name);
1523 /// }
1524 /// }
1525 /// # bevy_ecs::system::assert_is_system(print_selected_character_name_system);
1526 /// ```
1527 #[inline]
1528 pub fn get_inner(&self, entity: Entity) -> Result<ROQueryItem<'w, D>, QueryEntityError> {
1529 // SAFETY: system runs without conflicts with other systems.
1530 // same-system queries have runtime borrow checks when they conflict
1531 unsafe {
1532 self.state.as_readonly().get_unchecked_manual(
1533 self.world,
1534 entity,
1535 self.last_run,
1536 self.this_run,
1537 )
1538 }
1539 }
1540
1541 /// Returns an [`Iterator`] over the query items, with the actual "inner" world lifetime.
1542 ///
1543 /// This can only return immutable data (mutable data will be cast to an immutable form).
1544 /// See [`Self::iter_mut`] for queries that contain at least one mutable component.
1545 ///
1546 /// # Example
1547 ///
1548 /// Here, the `report_names_system` iterates over the `Player` component of every entity
1549 /// that contains it:
1550 ///
1551 /// ```
1552 /// # use bevy_ecs::prelude::*;
1553 /// #
1554 /// # #[derive(Component)]
1555 /// # struct Player { name: String }
1556 /// #
1557 /// fn report_names_system(query: Query<&Player>) {
1558 /// for player in &query {
1559 /// println!("Say hello to {}!", player.name);
1560 /// }
1561 /// }
1562 /// # bevy_ecs::system::assert_is_system(report_names_system);
1563 /// ```
1564 #[inline]
1565 pub fn iter_inner(&self) -> QueryIter<'w, 's, D::ReadOnly, F> {
1566 // SAFETY: system runs without conflicts with other systems.
1567 // same-system queries have runtime borrow checks when they conflict
1568 unsafe {
1569 self.state
1570 .as_readonly()
1571 .iter_unchecked_manual(self.world, self.last_run, self.this_run)
1572 }
1573 }
1574}
1575
1576/// Type returned from [`Query::transmute_lens`] containing the new [`QueryState`].
1577///
1578/// Call [`query`](QueryLens::query) or [`into`](Into::into) to construct the resulting [`Query`]
1579pub struct QueryLens<'w, Q: QueryData, F: QueryFilter = ()> {
1580 world: UnsafeWorldCell<'w>,
1581 state: QueryState<Q, F>,
1582 last_run: Tick,
1583 this_run: Tick,
1584}
1585
1586impl<'w, Q: QueryData, F: QueryFilter> QueryLens<'w, Q, F> {
1587 /// Create a [`Query`] from the underlying [`QueryState`].
1588 pub fn query(&mut self) -> Query<'w, '_, Q, F> {
1589 Query {
1590 world: self.world,
1591 state: &self.state,
1592 last_run: self.last_run,
1593 this_run: self.this_run,
1594 }
1595 }
1596}
1597
1598impl<'w, 's, Q: QueryData, F: QueryFilter> From<&'s mut QueryLens<'w, Q, F>>
1599 for Query<'w, 's, Q, F>
1600{
1601 fn from(value: &'s mut QueryLens<'w, Q, F>) -> Query<'w, 's, Q, F> {
1602 value.query()
1603 }
1604}
1605
1606impl<'w, 'q, Q: QueryData, F: QueryFilter> From<&'q mut Query<'w, '_, Q, F>>
1607 for QueryLens<'q, Q, F>
1608{
1609 fn from(value: &'q mut Query<'w, '_, Q, F>) -> QueryLens<'q, Q, F> {
1610 value.transmute_lens_filtered()
1611 }
1612}