bevy_ecs/query/
fetch.rs

1use crate::{
2    archetype::{Archetype, Archetypes},
3    bundle::Bundle,
4    change_detection::{MaybeThinSlicePtrLocation, Ticks, TicksMut},
5    component::{Component, ComponentId, Components, StorageType, Tick},
6    entity::{Entities, Entity, EntityLocation},
7    query::{Access, DebugCheckedUnwrap, FilteredAccess, WorldQuery},
8    storage::{ComponentSparseSet, Table, TableRow},
9    world::{
10        unsafe_world_cell::UnsafeWorldCell, EntityMut, EntityMutExcept, EntityRef, EntityRefExcept,
11        FilteredEntityMut, FilteredEntityRef, Mut, Ref, World,
12    },
13};
14use bevy_ptr::{ThinSlicePtr, UnsafeCellDeref};
15use bevy_utils::all_tuples;
16use core::{cell::UnsafeCell, marker::PhantomData};
17use smallvec::SmallVec;
18
19/// Types that can be fetched from a [`World`] using a [`Query`].
20///
21/// There are many types that natively implement this trait:
22///
23/// - **Component references. (&T and &mut T)**
24///   Fetches a component by reference (immutably or mutably).
25/// - **`QueryData` tuples.**
26///   If every element of a tuple implements `QueryData`, then the tuple itself also implements the same trait.
27///   This enables a single `Query` to access multiple components.
28///   Due to the current lack of variadic generics in Rust, the trait has been implemented for tuples from 0 to 15 elements,
29///   but nesting of tuples allows infinite `WorldQuery`s.
30/// - **[`Entity`].**
31///   Gets the identifier of the queried entity.
32/// - **[`EntityLocation`].**
33///   Gets the location metadata of the queried entity.
34/// - **[`EntityRef`].**
35///   Read-only access to arbitrary components on the queried entity.
36/// - **[`EntityMut`].**
37///   Mutable access to arbitrary components on the queried entity.
38/// - **[`&Archetype`](Archetype).**
39///   Read-only access to the archetype-level metadata of the queried entity.
40/// - **[`Option`].**
41///   By default, a world query only tests entities that have the matching component types.
42///   Wrapping it into an `Option` will increase the query search space, and it will return `None` if an entity doesn't satisfy the `WorldQuery`.
43/// - **[`AnyOf`].**
44///   Equivalent to wrapping each world query inside it into an `Option`.
45/// - **[`Ref`].**
46///   Similar to change detection filters but it is used as a query fetch parameter.
47///   It exposes methods to check for changes to the wrapped component.
48/// - **[`Has`].**
49///   Returns a bool indicating whether the entity has the specified component.
50///
51/// Implementing the trait manually can allow for a fundamentally new type of behavior.
52///
53/// # Trait derivation
54///
55/// Query design can be easily structured by deriving `QueryData` for custom types.
56/// Despite the added complexity, this approach has several advantages over using `QueryData` tuples.
57/// The most relevant improvements are:
58///
59/// - Reusability across multiple systems.
60/// - There is no need to destructure a tuple since all fields are named.
61/// - Subqueries can be composed together to create a more complex query.
62/// - Methods can be implemented for the query items.
63/// - There is no hardcoded limit on the number of elements.
64///
65/// This trait can only be derived for structs, if each field also implements `QueryData`.
66///
67/// ```
68/// # use bevy_ecs::prelude::*;
69/// use bevy_ecs::query::QueryData;
70/// #
71/// # #[derive(Component)]
72/// # struct ComponentA;
73/// # #[derive(Component)]
74/// # struct ComponentB;
75///
76/// #[derive(QueryData)]
77/// struct MyQuery {
78///     entity: Entity,
79///     // It is required that all reference lifetimes are explicitly annotated, just like in any
80///     // struct. Each lifetime should be 'static.
81///     component_a: &'static ComponentA,
82///     component_b: &'static ComponentB,
83/// }
84///
85/// fn my_system(query: Query<MyQuery>) {
86///     for q in &query {
87///         q.component_a;
88///     }
89/// }
90/// # bevy_ecs::system::assert_is_system(my_system);
91/// ```
92///
93/// ## Macro expansion
94///
95/// Expanding the macro will declare one or three additional structs, depending on whether or not the struct is marked as mutable.
96/// For a struct named `X`, the additional structs will be:
97///
98/// |Struct name|`mutable` only|Description|
99/// |:---:|:---:|---|
100/// |`XItem`|---|The type of the query item for `X`|
101/// |`XReadOnlyItem`|✓|The type of the query item for `XReadOnly`|
102/// |`XReadOnly`|✓|[`ReadOnly`] variant of `X`|
103///
104/// ## Adding mutable references
105///
106/// Simply adding mutable references to a derived `QueryData` will result in a compilation error:
107///
108/// ```compile_fail
109/// # use bevy_ecs::prelude::*;
110/// # use bevy_ecs::query::QueryData;
111/// #
112/// # #[derive(Component)]
113/// # struct ComponentA;
114/// #
115/// #[derive(QueryData)]
116/// struct CustomQuery {
117///     component_a: &'static mut ComponentA,
118/// }
119/// ```
120///
121/// To grant mutable access to components, the struct must be marked with the `#[query_data(mutable)]` attribute.
122/// This will also create three more structs that will be used for accessing the query immutably (see table above).
123///
124/// ```
125/// # use bevy_ecs::prelude::*;
126/// # use bevy_ecs::query::QueryData;
127/// #
128/// # #[derive(Component)]
129/// # struct ComponentA;
130/// #
131/// #[derive(QueryData)]
132/// #[query_data(mutable)]
133/// struct CustomQuery {
134///     component_a: &'static mut ComponentA,
135/// }
136/// ```
137///
138/// ## Adding methods to query items
139///
140/// It is possible to add methods to query items in order to write reusable logic about related components.
141/// This will often make systems more readable because low level logic is moved out from them.
142/// It is done by adding `impl` blocks with methods for the `-Item` or `-ReadOnlyItem` generated structs.
143///
144/// ```
145/// # use bevy_ecs::prelude::*;
146/// # use bevy_ecs::query::QueryData;
147/// #
148/// #[derive(Component)]
149/// struct Health(f32);
150///
151/// #[derive(Component)]
152/// struct Buff(f32);
153///
154/// #[derive(QueryData)]
155/// #[query_data(mutable)]
156/// struct HealthQuery {
157///     health: &'static mut Health,
158///     buff: Option<&'static mut Buff>,
159/// }
160///
161/// // `HealthQueryItem` is only available when accessing the query with mutable methods.
162/// impl<'w> HealthQueryItem<'w> {
163///     fn damage(&mut self, value: f32) {
164///         self.health.0 -= value;
165///     }
166///
167///     fn total(&self) -> f32 {
168///         self.health.0 + self.buff.as_deref().map_or(0.0, |Buff(buff)| *buff)
169///     }
170/// }
171///
172/// // `HealthQueryReadOnlyItem` is only available when accessing the query with immutable methods.
173/// impl<'w> HealthQueryReadOnlyItem<'w> {
174///     fn total(&self) -> f32 {
175///         self.health.0 + self.buff.map_or(0.0, |Buff(buff)| *buff)
176///     }
177/// }
178///
179/// fn my_system(mut health_query: Query<HealthQuery>) {
180///     // The item returned by the iterator is of type `HealthQueryReadOnlyItem`.
181///     for health in health_query.iter() {
182///         println!("Total: {}", health.total());
183///     }
184///     // The item returned by the iterator is of type `HealthQueryItem`.
185///     for mut health in &mut health_query {
186///         health.damage(1.0);
187///         println!("Total (mut): {}", health.total());
188///     }
189/// }
190/// # bevy_ecs::system::assert_is_system(my_system);
191/// ```
192///
193/// ## Deriving traits for query items
194///
195/// The `QueryData` derive macro does not automatically implement the traits of the struct to the query item types.
196/// Something similar can be done by using the `#[query_data(derive(...))]` attribute.
197/// This will apply the listed derivable traits to the query item structs.
198///
199/// ```
200/// # use bevy_ecs::prelude::*;
201/// # use bevy_ecs::query::QueryData;
202/// #
203/// # #[derive(Component, Debug)]
204/// # struct ComponentA;
205/// #
206/// #[derive(QueryData)]
207/// #[query_data(mutable, derive(Debug))]
208/// struct CustomQuery {
209///     component_a: &'static ComponentA,
210/// }
211///
212/// // This function statically checks that `T` implements `Debug`.
213/// fn assert_debug<T: std::fmt::Debug>() {}
214///
215/// assert_debug::<CustomQueryItem>();
216/// assert_debug::<CustomQueryReadOnlyItem>();
217/// ```
218///
219/// ## Query composition
220///
221/// It is possible to use any `QueryData` as a field of another one.
222/// This means that a `QueryData` can also be used as a subquery, potentially in multiple places.
223///
224/// ```
225/// # use bevy_ecs::prelude::*;
226/// # use bevy_ecs::query::QueryData;
227/// #
228/// # #[derive(Component)]
229/// # struct ComponentA;
230/// # #[derive(Component)]
231/// # struct ComponentB;
232/// # #[derive(Component)]
233/// # struct ComponentC;
234/// #
235/// #[derive(QueryData)]
236/// struct SubQuery {
237///     component_a: &'static ComponentA,
238///     component_b: &'static ComponentB,
239/// }
240///
241/// #[derive(QueryData)]
242/// struct MyQuery {
243///     subquery: SubQuery,
244///     component_c: &'static ComponentC,
245/// }
246/// ```
247///
248/// # Generic Queries
249///
250/// When writing generic code, it is often necessary to use [`PhantomData`]
251/// to constrain type parameters. Since `QueryData` is implemented for all
252/// `PhantomData<T>` types, this pattern can be used with this macro.
253///
254/// ```
255/// # use bevy_ecs::{prelude::*, query::QueryData};
256/// # use std::marker::PhantomData;
257/// #[derive(QueryData)]
258/// pub struct GenericQuery<T> {
259///     id: Entity,
260///     marker: PhantomData<T>,
261/// }
262/// # fn my_system(q: Query<GenericQuery<()>>) {}
263/// # bevy_ecs::system::assert_is_system(my_system);
264/// ```
265///
266/// # Safety
267///
268/// Component access of `Self::ReadOnly` must be a subset of `Self`
269/// and `Self::ReadOnly` must match exactly the same archetypes/tables as `Self`
270///
271/// [`Query`]: crate::system::Query
272/// [`ReadOnly`]: Self::ReadOnly
273#[diagnostic::on_unimplemented(
274    message = "`{Self}` is not valid to request as data in a `Query`",
275    label = "invalid `Query` data",
276    note = "if `{Self}` is a component type, try using `&{Self}` or `&mut {Self}`"
277)]
278pub unsafe trait QueryData: WorldQuery {
279    /// The read-only variant of this [`QueryData`], which satisfies the [`ReadOnlyQueryData`] trait.
280    type ReadOnly: ReadOnlyQueryData<State = <Self as WorldQuery>::State>;
281}
282
283/// A [`QueryData`] that is read only.
284///
285/// # Safety
286///
287/// This must only be implemented for read-only [`QueryData`]'s.
288pub unsafe trait ReadOnlyQueryData: QueryData<ReadOnly = Self> {}
289
290/// The item type returned when a [`WorldQuery`] is iterated over
291pub type QueryItem<'w, Q> = <Q as WorldQuery>::Item<'w>;
292/// The read-only variant of the item type returned when a [`QueryData`] is iterated over immutably
293pub type ROQueryItem<'w, D> = QueryItem<'w, <D as QueryData>::ReadOnly>;
294
295/// SAFETY:
296/// `update_component_access` and `update_archetype_component_access` do nothing.
297/// This is sound because `fetch` does not access components.
298unsafe impl WorldQuery for Entity {
299    type Item<'w> = Entity;
300    type Fetch<'w> = ();
301    type State = ();
302
303    fn shrink<'wlong: 'wshort, 'wshort>(item: Self::Item<'wlong>) -> Self::Item<'wshort> {
304        item
305    }
306
307    fn shrink_fetch<'wlong: 'wshort, 'wshort>(_: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {}
308
309    unsafe fn init_fetch<'w>(
310        _world: UnsafeWorldCell<'w>,
311        _state: &Self::State,
312        _last_run: Tick,
313        _this_run: Tick,
314    ) -> Self::Fetch<'w> {
315    }
316
317    const IS_DENSE: bool = true;
318
319    #[inline]
320    unsafe fn set_archetype<'w>(
321        _fetch: &mut Self::Fetch<'w>,
322        _state: &Self::State,
323        _archetype: &'w Archetype,
324        _table: &Table,
325    ) {
326    }
327
328    #[inline]
329    unsafe fn set_table<'w>(_fetch: &mut Self::Fetch<'w>, _state: &Self::State, _table: &'w Table) {
330    }
331
332    #[inline(always)]
333    unsafe fn fetch<'w>(
334        _fetch: &mut Self::Fetch<'w>,
335        entity: Entity,
336        _table_row: TableRow,
337    ) -> Self::Item<'w> {
338        entity
339    }
340
341    fn update_component_access(_state: &Self::State, _access: &mut FilteredAccess<ComponentId>) {}
342
343    fn init_state(_world: &mut World) {}
344
345    fn get_state(_components: &Components) -> Option<()> {
346        Some(())
347    }
348
349    fn matches_component_set(
350        _state: &Self::State,
351        _set_contains_id: &impl Fn(ComponentId) -> bool,
352    ) -> bool {
353        true
354    }
355}
356
357/// SAFETY: `Self` is the same as `Self::ReadOnly`
358unsafe impl QueryData for Entity {
359    type ReadOnly = Self;
360}
361
362/// SAFETY: access is read only
363unsafe impl ReadOnlyQueryData for Entity {}
364
365/// SAFETY:
366/// `update_component_access` and `update_archetype_component_access` do nothing.
367/// This is sound because `fetch` does not access components.
368unsafe impl WorldQuery for EntityLocation {
369    type Item<'w> = EntityLocation;
370    type Fetch<'w> = &'w Entities;
371    type State = ();
372
373    fn shrink<'wlong: 'wshort, 'wshort>(item: Self::Item<'wlong>) -> Self::Item<'wshort> {
374        item
375    }
376
377    fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {
378        fetch
379    }
380
381    unsafe fn init_fetch<'w>(
382        world: UnsafeWorldCell<'w>,
383        _state: &Self::State,
384        _last_run: Tick,
385        _this_run: Tick,
386    ) -> Self::Fetch<'w> {
387        world.entities()
388    }
389
390    // This is set to true to avoid forcing archetypal iteration in compound queries, is likely to be slower
391    // in most practical use case.
392    const IS_DENSE: bool = true;
393
394    #[inline]
395    unsafe fn set_archetype<'w>(
396        _fetch: &mut Self::Fetch<'w>,
397        _state: &Self::State,
398        _archetype: &'w Archetype,
399        _table: &Table,
400    ) {
401    }
402
403    #[inline]
404    unsafe fn set_table<'w>(_fetch: &mut Self::Fetch<'w>, _state: &Self::State, _table: &'w Table) {
405    }
406
407    #[inline(always)]
408    unsafe fn fetch<'w>(
409        fetch: &mut Self::Fetch<'w>,
410        entity: Entity,
411        _table_row: TableRow,
412    ) -> Self::Item<'w> {
413        // SAFETY: `fetch` must be called with an entity that exists in the world
414        unsafe { fetch.get(entity).debug_checked_unwrap() }
415    }
416
417    fn update_component_access(_state: &Self::State, _access: &mut FilteredAccess<ComponentId>) {}
418
419    fn init_state(_world: &mut World) {}
420
421    fn get_state(_components: &Components) -> Option<()> {
422        Some(())
423    }
424
425    fn matches_component_set(
426        _state: &Self::State,
427        _set_contains_id: &impl Fn(ComponentId) -> bool,
428    ) -> bool {
429        true
430    }
431}
432
433/// SAFETY: `Self` is the same as `Self::ReadOnly`
434unsafe impl QueryData for EntityLocation {
435    type ReadOnly = Self;
436}
437
438/// SAFETY: access is read only
439unsafe impl ReadOnlyQueryData for EntityLocation {}
440
441/// SAFETY:
442/// `fetch` accesses all components in a readonly way.
443/// This is sound because `update_component_access` and `update_archetype_component_access` set read access for all components and panic when appropriate.
444/// Filters are unchanged.
445unsafe impl<'a> WorldQuery for EntityRef<'a> {
446    type Item<'w> = EntityRef<'w>;
447    type Fetch<'w> = UnsafeWorldCell<'w>;
448    type State = ();
449
450    fn shrink<'wlong: 'wshort, 'wshort>(item: Self::Item<'wlong>) -> Self::Item<'wshort> {
451        item
452    }
453
454    fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {
455        fetch
456    }
457
458    unsafe fn init_fetch<'w>(
459        world: UnsafeWorldCell<'w>,
460        _state: &Self::State,
461        _last_run: Tick,
462        _this_run: Tick,
463    ) -> Self::Fetch<'w> {
464        world
465    }
466
467    const IS_DENSE: bool = true;
468
469    #[inline]
470    unsafe fn set_archetype<'w>(
471        _fetch: &mut Self::Fetch<'w>,
472        _state: &Self::State,
473        _archetype: &'w Archetype,
474        _table: &Table,
475    ) {
476    }
477
478    #[inline]
479    unsafe fn set_table<'w>(_fetch: &mut Self::Fetch<'w>, _state: &Self::State, _table: &'w Table) {
480    }
481
482    #[inline(always)]
483    unsafe fn fetch<'w>(
484        world: &mut Self::Fetch<'w>,
485        entity: Entity,
486        _table_row: TableRow,
487    ) -> Self::Item<'w> {
488        // SAFETY: `fetch` must be called with an entity that exists in the world
489        let cell = unsafe { world.get_entity(entity).debug_checked_unwrap() };
490        // SAFETY: Read-only access to every component has been registered.
491        unsafe { EntityRef::new(cell) }
492    }
493
494    fn update_component_access(_state: &Self::State, access: &mut FilteredAccess<ComponentId>) {
495        assert!(
496            !access.access().has_any_component_write(),
497            "EntityRef conflicts with a previous access in this query. Shared access cannot coincide with exclusive access.",
498        );
499        access.read_all_components();
500    }
501
502    fn init_state(_world: &mut World) {}
503
504    fn get_state(_components: &Components) -> Option<()> {
505        Some(())
506    }
507
508    fn matches_component_set(
509        _state: &Self::State,
510        _set_contains_id: &impl Fn(ComponentId) -> bool,
511    ) -> bool {
512        true
513    }
514}
515
516/// SAFETY: `Self` is the same as `Self::ReadOnly`
517unsafe impl<'a> QueryData for EntityRef<'a> {
518    type ReadOnly = Self;
519}
520
521/// SAFETY: access is read only
522unsafe impl ReadOnlyQueryData for EntityRef<'_> {}
523
524/// SAFETY: The accesses of `Self::ReadOnly` are a subset of the accesses of `Self`
525unsafe impl<'a> WorldQuery for EntityMut<'a> {
526    type Item<'w> = EntityMut<'w>;
527    type Fetch<'w> = UnsafeWorldCell<'w>;
528    type State = ();
529
530    fn shrink<'wlong: 'wshort, 'wshort>(item: Self::Item<'wlong>) -> Self::Item<'wshort> {
531        item
532    }
533
534    fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {
535        fetch
536    }
537
538    unsafe fn init_fetch<'w>(
539        world: UnsafeWorldCell<'w>,
540        _state: &Self::State,
541        _last_run: Tick,
542        _this_run: Tick,
543    ) -> Self::Fetch<'w> {
544        world
545    }
546
547    const IS_DENSE: bool = true;
548
549    #[inline]
550    unsafe fn set_archetype<'w>(
551        _fetch: &mut Self::Fetch<'w>,
552        _state: &Self::State,
553        _archetype: &'w Archetype,
554        _table: &Table,
555    ) {
556    }
557
558    #[inline]
559    unsafe fn set_table<'w>(_fetch: &mut Self::Fetch<'w>, _state: &Self::State, _table: &'w Table) {
560    }
561
562    #[inline(always)]
563    unsafe fn fetch<'w>(
564        world: &mut Self::Fetch<'w>,
565        entity: Entity,
566        _table_row: TableRow,
567    ) -> Self::Item<'w> {
568        // SAFETY: `fetch` must be called with an entity that exists in the world
569        let cell = unsafe { world.get_entity(entity).debug_checked_unwrap() };
570        // SAFETY: mutable access to every component has been registered.
571        unsafe { EntityMut::new(cell) }
572    }
573
574    fn update_component_access(_state: &Self::State, access: &mut FilteredAccess<ComponentId>) {
575        assert!(
576            !access.access().has_any_component_read(),
577            "EntityMut conflicts with a previous access in this query. Exclusive access cannot coincide with any other accesses.",
578        );
579        access.write_all_components();
580    }
581
582    fn init_state(_world: &mut World) {}
583
584    fn get_state(_components: &Components) -> Option<()> {
585        Some(())
586    }
587
588    fn matches_component_set(
589        _state: &Self::State,
590        _set_contains_id: &impl Fn(ComponentId) -> bool,
591    ) -> bool {
592        true
593    }
594}
595
596/// SAFETY: access of `EntityRef` is a subset of `EntityMut`
597unsafe impl<'a> QueryData for EntityMut<'a> {
598    type ReadOnly = EntityRef<'a>;
599}
600
601/// SAFETY: The accesses of `Self::ReadOnly` are a subset of the accesses of `Self`
602unsafe impl<'a> WorldQuery for FilteredEntityRef<'a> {
603    type Fetch<'w> = (UnsafeWorldCell<'w>, Access<ComponentId>);
604    type Item<'w> = FilteredEntityRef<'w>;
605    type State = FilteredAccess<ComponentId>;
606
607    fn shrink<'wlong: 'wshort, 'wshort>(item: Self::Item<'wlong>) -> Self::Item<'wshort> {
608        item
609    }
610
611    fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {
612        fetch
613    }
614
615    const IS_DENSE: bool = false;
616
617    unsafe fn init_fetch<'w>(
618        world: UnsafeWorldCell<'w>,
619        _state: &Self::State,
620        _last_run: Tick,
621        _this_run: Tick,
622    ) -> Self::Fetch<'w> {
623        let mut access = Access::default();
624        access.read_all_components();
625        (world, access)
626    }
627
628    #[inline]
629    unsafe fn set_archetype<'w>(
630        fetch: &mut Self::Fetch<'w>,
631        state: &Self::State,
632        _: &'w Archetype,
633        _table: &Table,
634    ) {
635        fetch.1.clone_from(&state.access);
636    }
637
638    #[inline]
639    unsafe fn set_table<'w>(fetch: &mut Self::Fetch<'w>, state: &Self::State, _: &'w Table) {
640        fetch.1.clone_from(&state.access);
641    }
642
643    #[inline]
644    fn set_access<'w>(state: &mut Self::State, access: &FilteredAccess<ComponentId>) {
645        state.clone_from(access);
646        state.access_mut().clear_writes();
647    }
648
649    #[inline(always)]
650    unsafe fn fetch<'w>(
651        (world, access): &mut Self::Fetch<'w>,
652        entity: Entity,
653        _table_row: TableRow,
654    ) -> Self::Item<'w> {
655        // SAFETY: `fetch` must be called with an entity that exists in the world
656        let cell = unsafe { world.get_entity(entity).debug_checked_unwrap() };
657        // SAFETY: mutable access to every component has been registered.
658        unsafe { FilteredEntityRef::new(cell, access.clone()) }
659    }
660
661    fn update_component_access(
662        state: &Self::State,
663        filtered_access: &mut FilteredAccess<ComponentId>,
664    ) {
665        assert!(
666            filtered_access.access().is_compatible(&state.access),
667            "FilteredEntityRef conflicts with a previous access in this query. Exclusive access cannot coincide with any other accesses.",
668        );
669        filtered_access.access.extend(&state.access);
670    }
671
672    fn init_state(_world: &mut World) -> Self::State {
673        FilteredAccess::default()
674    }
675
676    fn get_state(_components: &Components) -> Option<Self::State> {
677        Some(FilteredAccess::default())
678    }
679
680    fn matches_component_set(
681        _state: &Self::State,
682        _set_contains_id: &impl Fn(ComponentId) -> bool,
683    ) -> bool {
684        true
685    }
686}
687
688/// SAFETY: `Self` is the same as `Self::ReadOnly`
689unsafe impl<'a> QueryData for FilteredEntityRef<'a> {
690    type ReadOnly = Self;
691}
692
693/// SAFETY: Access is read-only.
694unsafe impl ReadOnlyQueryData for FilteredEntityRef<'_> {}
695
696/// SAFETY: The accesses of `Self::ReadOnly` are a subset of the accesses of `Self`
697unsafe impl<'a> WorldQuery for FilteredEntityMut<'a> {
698    type Fetch<'w> = (UnsafeWorldCell<'w>, Access<ComponentId>);
699    type Item<'w> = FilteredEntityMut<'w>;
700    type State = FilteredAccess<ComponentId>;
701
702    fn shrink<'wlong: 'wshort, 'wshort>(item: Self::Item<'wlong>) -> Self::Item<'wshort> {
703        item
704    }
705
706    fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {
707        fetch
708    }
709
710    const IS_DENSE: bool = false;
711
712    unsafe fn init_fetch<'w>(
713        world: UnsafeWorldCell<'w>,
714        _state: &Self::State,
715        _last_run: Tick,
716        _this_run: Tick,
717    ) -> Self::Fetch<'w> {
718        let mut access = Access::default();
719        access.write_all_components();
720        (world, access)
721    }
722
723    #[inline]
724    unsafe fn set_archetype<'w>(
725        fetch: &mut Self::Fetch<'w>,
726        state: &Self::State,
727        _: &'w Archetype,
728        _table: &Table,
729    ) {
730        fetch.1.clone_from(&state.access);
731    }
732
733    #[inline]
734    unsafe fn set_table<'w>(fetch: &mut Self::Fetch<'w>, state: &Self::State, _: &'w Table) {
735        fetch.1.clone_from(&state.access);
736    }
737
738    #[inline]
739    fn set_access<'w>(state: &mut Self::State, access: &FilteredAccess<ComponentId>) {
740        state.clone_from(access);
741    }
742
743    #[inline(always)]
744    unsafe fn fetch<'w>(
745        (world, access): &mut Self::Fetch<'w>,
746        entity: Entity,
747        _table_row: TableRow,
748    ) -> Self::Item<'w> {
749        // SAFETY: `fetch` must be called with an entity that exists in the world
750        let cell = unsafe { world.get_entity(entity).debug_checked_unwrap() };
751        // SAFETY: mutable access to every component has been registered.
752        unsafe { FilteredEntityMut::new(cell, access.clone()) }
753    }
754
755    fn update_component_access(
756        state: &Self::State,
757        filtered_access: &mut FilteredAccess<ComponentId>,
758    ) {
759        assert!(
760            filtered_access.access().is_compatible(&state.access),
761            "FilteredEntityMut conflicts with a previous access in this query. Exclusive access cannot coincide with any other accesses.",
762        );
763        filtered_access.access.extend(&state.access);
764    }
765
766    fn init_state(_world: &mut World) -> Self::State {
767        FilteredAccess::default()
768    }
769
770    fn get_state(_components: &Components) -> Option<Self::State> {
771        Some(FilteredAccess::default())
772    }
773
774    fn matches_component_set(
775        _state: &Self::State,
776        _set_contains_id: &impl Fn(ComponentId) -> bool,
777    ) -> bool {
778        true
779    }
780}
781
782/// SAFETY: access of `FilteredEntityRef` is a subset of `FilteredEntityMut`
783unsafe impl<'a> QueryData for FilteredEntityMut<'a> {
784    type ReadOnly = FilteredEntityRef<'a>;
785}
786
787/// SAFETY: `EntityRefExcept` guards access to all components in the bundle `B`
788/// and populates `Access` values so that queries that conflict with this access
789/// are rejected.
790unsafe impl<'a, B> WorldQuery for EntityRefExcept<'a, B>
791where
792    B: Bundle,
793{
794    type Fetch<'w> = UnsafeWorldCell<'w>;
795    type Item<'w> = EntityRefExcept<'w, B>;
796    type State = SmallVec<[ComponentId; 4]>;
797
798    fn shrink<'wlong: 'wshort, 'wshort>(item: Self::Item<'wlong>) -> Self::Item<'wshort> {
799        item
800    }
801
802    fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {
803        fetch
804    }
805
806    unsafe fn init_fetch<'w>(
807        world: UnsafeWorldCell<'w>,
808        _: &Self::State,
809        _: Tick,
810        _: Tick,
811    ) -> Self::Fetch<'w> {
812        world
813    }
814
815    const IS_DENSE: bool = true;
816
817    unsafe fn set_archetype<'w>(
818        _: &mut Self::Fetch<'w>,
819        _: &Self::State,
820        _: &'w Archetype,
821        _: &'w Table,
822    ) {
823    }
824
825    unsafe fn set_table<'w>(_: &mut Self::Fetch<'w>, _: &Self::State, _: &'w Table) {}
826
827    unsafe fn fetch<'w>(
828        world: &mut Self::Fetch<'w>,
829        entity: Entity,
830        _: TableRow,
831    ) -> Self::Item<'w> {
832        let cell = world.get_entity(entity).unwrap();
833        EntityRefExcept::new(cell)
834    }
835
836    fn update_component_access(
837        state: &Self::State,
838        filtered_access: &mut FilteredAccess<ComponentId>,
839    ) {
840        let mut my_access = Access::new();
841        my_access.read_all_components();
842        for id in state {
843            my_access.remove_component_read(*id);
844        }
845
846        let access = filtered_access.access_mut();
847        assert!(
848            access.is_compatible(&my_access),
849            "`EntityRefExcept<{}>` conflicts with a previous access in this query.",
850            core::any::type_name::<B>(),
851        );
852        access.extend(&my_access);
853    }
854
855    fn init_state(world: &mut World) -> Self::State {
856        Self::get_state(world.components()).unwrap()
857    }
858
859    fn get_state(components: &Components) -> Option<Self::State> {
860        let mut ids = SmallVec::new();
861        B::get_component_ids(components, &mut |maybe_id| {
862            if let Some(id) = maybe_id {
863                ids.push(id);
864            }
865        });
866        Some(ids)
867    }
868
869    fn matches_component_set(_: &Self::State, _: &impl Fn(ComponentId) -> bool) -> bool {
870        true
871    }
872}
873
874/// SAFETY: `Self` is the same as `Self::ReadOnly`.
875unsafe impl<'a, B> QueryData for EntityRefExcept<'a, B>
876where
877    B: Bundle,
878{
879    type ReadOnly = Self;
880}
881
882/// SAFETY: `EntityRefExcept` enforces read-only access to its contained
883/// components.
884unsafe impl<'a, B> ReadOnlyQueryData for EntityRefExcept<'a, B> where B: Bundle {}
885
886/// SAFETY: `EntityMutExcept` guards access to all components in the bundle `B`
887/// and populates `Access` values so that queries that conflict with this access
888/// are rejected.
889unsafe impl<'a, B> WorldQuery for EntityMutExcept<'a, B>
890where
891    B: Bundle,
892{
893    type Fetch<'w> = UnsafeWorldCell<'w>;
894    type Item<'w> = EntityMutExcept<'w, B>;
895    type State = SmallVec<[ComponentId; 4]>;
896
897    fn shrink<'wlong: 'wshort, 'wshort>(item: Self::Item<'wlong>) -> Self::Item<'wshort> {
898        item
899    }
900
901    fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {
902        fetch
903    }
904
905    unsafe fn init_fetch<'w>(
906        world: UnsafeWorldCell<'w>,
907        _: &Self::State,
908        _: Tick,
909        _: Tick,
910    ) -> Self::Fetch<'w> {
911        world
912    }
913
914    const IS_DENSE: bool = true;
915
916    unsafe fn set_archetype<'w>(
917        _: &mut Self::Fetch<'w>,
918        _: &Self::State,
919        _: &'w Archetype,
920        _: &'w Table,
921    ) {
922    }
923
924    unsafe fn set_table<'w>(_: &mut Self::Fetch<'w>, _: &Self::State, _: &'w Table) {}
925
926    unsafe fn fetch<'w>(
927        world: &mut Self::Fetch<'w>,
928        entity: Entity,
929        _: TableRow,
930    ) -> Self::Item<'w> {
931        let cell = world.get_entity(entity).unwrap();
932        EntityMutExcept::new(cell)
933    }
934
935    fn update_component_access(
936        state: &Self::State,
937        filtered_access: &mut FilteredAccess<ComponentId>,
938    ) {
939        let mut my_access = Access::new();
940        my_access.write_all_components();
941        for id in state {
942            my_access.remove_component_read(*id);
943        }
944
945        let access = filtered_access.access_mut();
946        assert!(
947            access.is_compatible(&my_access),
948            "`EntityMutExcept<{}>` conflicts with a previous access in this query.",
949            core::any::type_name::<B>()
950        );
951        access.extend(&my_access);
952    }
953
954    fn init_state(world: &mut World) -> Self::State {
955        Self::get_state(world.components()).unwrap()
956    }
957
958    fn get_state(components: &Components) -> Option<Self::State> {
959        let mut ids = SmallVec::new();
960        B::get_component_ids(components, &mut |maybe_id| {
961            if let Some(id) = maybe_id {
962                ids.push(id);
963            }
964        });
965        Some(ids)
966    }
967
968    fn matches_component_set(_: &Self::State, _: &impl Fn(ComponentId) -> bool) -> bool {
969        true
970    }
971}
972
973/// SAFETY: All accesses that `EntityRefExcept` provides are also accesses that
974/// `EntityMutExcept` provides.
975unsafe impl<'a, B> QueryData for EntityMutExcept<'a, B>
976where
977    B: Bundle,
978{
979    type ReadOnly = EntityRefExcept<'a, B>;
980}
981
982/// SAFETY:
983/// `update_component_access` and `update_archetype_component_access` do nothing.
984/// This is sound because `fetch` does not access components.
985unsafe impl WorldQuery for &Archetype {
986    type Item<'w> = &'w Archetype;
987    type Fetch<'w> = (&'w Entities, &'w Archetypes);
988    type State = ();
989
990    fn shrink<'wlong: 'wshort, 'wshort>(item: Self::Item<'wlong>) -> Self::Item<'wshort> {
991        item
992    }
993
994    fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {
995        fetch
996    }
997
998    unsafe fn init_fetch<'w>(
999        world: UnsafeWorldCell<'w>,
1000        _state: &Self::State,
1001        _last_run: Tick,
1002        _this_run: Tick,
1003    ) -> Self::Fetch<'w> {
1004        (world.entities(), world.archetypes())
1005    }
1006
1007    // This could probably be a non-dense query and just set a Option<&Archetype> fetch value in
1008    // set_archetypes, but forcing archetypal iteration is likely to be slower in any compound query.
1009    const IS_DENSE: bool = true;
1010
1011    #[inline]
1012    unsafe fn set_archetype<'w>(
1013        _fetch: &mut Self::Fetch<'w>,
1014        _state: &Self::State,
1015        _archetype: &'w Archetype,
1016        _table: &Table,
1017    ) {
1018    }
1019
1020    #[inline]
1021    unsafe fn set_table<'w>(_fetch: &mut Self::Fetch<'w>, _state: &Self::State, _table: &'w Table) {
1022    }
1023
1024    #[inline(always)]
1025    unsafe fn fetch<'w>(
1026        fetch: &mut Self::Fetch<'w>,
1027        entity: Entity,
1028        _table_row: TableRow,
1029    ) -> Self::Item<'w> {
1030        let (entities, archetypes) = *fetch;
1031        // SAFETY: `fetch` must be called with an entity that exists in the world
1032        let location = unsafe { entities.get(entity).debug_checked_unwrap() };
1033        // SAFETY: The assigned archetype for a living entity must always be valid.
1034        unsafe { archetypes.get(location.archetype_id).debug_checked_unwrap() }
1035    }
1036
1037    fn update_component_access(_state: &Self::State, _access: &mut FilteredAccess<ComponentId>) {}
1038
1039    fn init_state(_world: &mut World) {}
1040
1041    fn get_state(_components: &Components) -> Option<()> {
1042        Some(())
1043    }
1044
1045    fn matches_component_set(
1046        _state: &Self::State,
1047        _set_contains_id: &impl Fn(ComponentId) -> bool,
1048    ) -> bool {
1049        true
1050    }
1051}
1052
1053/// SAFETY: `Self` is the same as `Self::ReadOnly`
1054unsafe impl QueryData for &Archetype {
1055    type ReadOnly = Self;
1056}
1057
1058/// SAFETY: access is read only
1059unsafe impl ReadOnlyQueryData for &Archetype {}
1060
1061/// The [`WorldQuery::Fetch`] type for `& T`.
1062pub struct ReadFetch<'w, T: Component> {
1063    components: StorageSwitch<
1064        T,
1065        // T::STORAGE_TYPE = StorageType::Table
1066        Option<ThinSlicePtr<'w, UnsafeCell<T>>>,
1067        // T::STORAGE_TYPE = StorageType::SparseSet
1068        &'w ComponentSparseSet,
1069    >,
1070}
1071
1072impl<T: Component> Clone for ReadFetch<'_, T> {
1073    fn clone(&self) -> Self {
1074        *self
1075    }
1076}
1077impl<T: Component> Copy for ReadFetch<'_, T> {}
1078
1079/// SAFETY:
1080/// `fetch` accesses a single component in a readonly way.
1081/// This is sound because `update_component_access` and `update_archetype_component_access` add read access for that component and panic when appropriate.
1082/// `update_component_access` adds a `With` filter for a component.
1083/// This is sound because `matches_component_set` returns whether the set contains that component.
1084unsafe impl<T: Component> WorldQuery for &T {
1085    type Item<'w> = &'w T;
1086    type Fetch<'w> = ReadFetch<'w, T>;
1087    type State = ComponentId;
1088
1089    fn shrink<'wlong: 'wshort, 'wshort>(item: &'wlong T) -> &'wshort T {
1090        item
1091    }
1092
1093    fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {
1094        fetch
1095    }
1096
1097    #[inline]
1098    unsafe fn init_fetch<'w>(
1099        world: UnsafeWorldCell<'w>,
1100        &component_id: &ComponentId,
1101        _last_run: Tick,
1102        _this_run: Tick,
1103    ) -> ReadFetch<'w, T> {
1104        ReadFetch {
1105            components: StorageSwitch::new(
1106                || None,
1107                || {
1108                    // SAFETY: The underlying type associated with `component_id` is `T`,
1109                    // which we are allowed to access since we registered it in `update_archetype_component_access`.
1110                    // Note that we do not actually access any components in this function, we just get a shared
1111                    // reference to the sparse set, which is used to access the components in `Self::fetch`.
1112                    unsafe {
1113                        world
1114                            .storages()
1115                            .sparse_sets
1116                            .get(component_id)
1117                            .debug_checked_unwrap()
1118                    }
1119                },
1120            ),
1121        }
1122    }
1123
1124    const IS_DENSE: bool = {
1125        match T::STORAGE_TYPE {
1126            StorageType::Table => true,
1127            StorageType::SparseSet => false,
1128        }
1129    };
1130
1131    #[inline]
1132    unsafe fn set_archetype<'w>(
1133        fetch: &mut ReadFetch<'w, T>,
1134        component_id: &ComponentId,
1135        _archetype: &'w Archetype,
1136        table: &'w Table,
1137    ) {
1138        if Self::IS_DENSE {
1139            // SAFETY: `set_archetype`'s safety rules are a super set of the `set_table`'s ones.
1140            unsafe {
1141                Self::set_table(fetch, component_id, table);
1142            }
1143        }
1144    }
1145
1146    #[inline]
1147    unsafe fn set_table<'w>(
1148        fetch: &mut ReadFetch<'w, T>,
1149        &component_id: &ComponentId,
1150        table: &'w Table,
1151    ) {
1152        let table_data = Some(
1153            table
1154                .get_data_slice_for(component_id)
1155                .debug_checked_unwrap()
1156                .into(),
1157        );
1158        // SAFETY: set_table is only called when T::STORAGE_TYPE = StorageType::Table
1159        unsafe { fetch.components.set_table(table_data) };
1160    }
1161
1162    #[inline(always)]
1163    unsafe fn fetch<'w>(
1164        fetch: &mut Self::Fetch<'w>,
1165        entity: Entity,
1166        table_row: TableRow,
1167    ) -> Self::Item<'w> {
1168        fetch.components.extract(
1169            |table| {
1170                // SAFETY: set_table was previously called
1171                let table = unsafe { table.debug_checked_unwrap() };
1172                // SAFETY: Caller ensures `table_row` is in range.
1173                let item = unsafe { table.get(table_row.as_usize()) };
1174                item.deref()
1175            },
1176            |sparse_set| {
1177                // SAFETY: Caller ensures `entity` is in range.
1178                let item = unsafe { sparse_set.get(entity).debug_checked_unwrap() };
1179                item.deref()
1180            },
1181        )
1182    }
1183
1184    fn update_component_access(
1185        &component_id: &ComponentId,
1186        access: &mut FilteredAccess<ComponentId>,
1187    ) {
1188        assert!(
1189            !access.access().has_component_write(component_id),
1190            "&{} conflicts with a previous access in this query. Shared access cannot coincide with exclusive access.",
1191            core::any::type_name::<T>(),
1192        );
1193        access.add_component_read(component_id);
1194    }
1195
1196    fn init_state(world: &mut World) -> ComponentId {
1197        world.register_component::<T>()
1198    }
1199
1200    fn get_state(components: &Components) -> Option<Self::State> {
1201        components.component_id::<T>()
1202    }
1203
1204    fn matches_component_set(
1205        &state: &ComponentId,
1206        set_contains_id: &impl Fn(ComponentId) -> bool,
1207    ) -> bool {
1208        set_contains_id(state)
1209    }
1210}
1211
1212/// SAFETY: `Self` is the same as `Self::ReadOnly`
1213unsafe impl<T: Component> QueryData for &T {
1214    type ReadOnly = Self;
1215}
1216
1217/// SAFETY: access is read only
1218unsafe impl<T: Component> ReadOnlyQueryData for &T {}
1219
1220#[doc(hidden)]
1221pub struct RefFetch<'w, T: Component> {
1222    components: StorageSwitch<
1223        T,
1224        // T::STORAGE_TYPE = StorageType::Table
1225        Option<(
1226            ThinSlicePtr<'w, UnsafeCell<T>>,
1227            ThinSlicePtr<'w, UnsafeCell<Tick>>,
1228            ThinSlicePtr<'w, UnsafeCell<Tick>>,
1229            MaybeThinSlicePtrLocation<'w>,
1230        )>,
1231        // T::STORAGE_TYPE = StorageType::SparseSet
1232        &'w ComponentSparseSet,
1233    >,
1234    last_run: Tick,
1235    this_run: Tick,
1236}
1237
1238impl<T: Component> Clone for RefFetch<'_, T> {
1239    fn clone(&self) -> Self {
1240        *self
1241    }
1242}
1243impl<T: Component> Copy for RefFetch<'_, T> {}
1244
1245/// SAFETY:
1246/// `fetch` accesses a single component in a readonly way.
1247/// This is sound because `update_component_access` and `update_archetype_component_access` add read access for that component and panic when appropriate.
1248/// `update_component_access` adds a `With` filter for a component.
1249/// This is sound because `matches_component_set` returns whether the set contains that component.
1250unsafe impl<'__w, T: Component> WorldQuery for Ref<'__w, T> {
1251    type Item<'w> = Ref<'w, T>;
1252    type Fetch<'w> = RefFetch<'w, T>;
1253    type State = ComponentId;
1254
1255    fn shrink<'wlong: 'wshort, 'wshort>(item: Ref<'wlong, T>) -> Ref<'wshort, T> {
1256        item
1257    }
1258
1259    fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {
1260        fetch
1261    }
1262
1263    #[inline]
1264    unsafe fn init_fetch<'w>(
1265        world: UnsafeWorldCell<'w>,
1266        &component_id: &ComponentId,
1267        last_run: Tick,
1268        this_run: Tick,
1269    ) -> RefFetch<'w, T> {
1270        RefFetch {
1271            components: StorageSwitch::new(
1272                || None,
1273                || {
1274                    // SAFETY: The underlying type associated with `component_id` is `T`,
1275                    // which we are allowed to access since we registered it in `update_archetype_component_access`.
1276                    // Note that we do not actually access any components in this function, we just get a shared
1277                    // reference to the sparse set, which is used to access the components in `Self::fetch`.
1278                    unsafe {
1279                        world
1280                            .storages()
1281                            .sparse_sets
1282                            .get(component_id)
1283                            .debug_checked_unwrap()
1284                    }
1285                },
1286            ),
1287            last_run,
1288            this_run,
1289        }
1290    }
1291
1292    const IS_DENSE: bool = {
1293        match T::STORAGE_TYPE {
1294            StorageType::Table => true,
1295            StorageType::SparseSet => false,
1296        }
1297    };
1298
1299    #[inline]
1300    unsafe fn set_archetype<'w>(
1301        fetch: &mut RefFetch<'w, T>,
1302        component_id: &ComponentId,
1303        _archetype: &'w Archetype,
1304        table: &'w Table,
1305    ) {
1306        if Self::IS_DENSE {
1307            // SAFETY: `set_archetype`'s safety rules are a super set of the `set_table`'s ones.
1308            unsafe {
1309                Self::set_table(fetch, component_id, table);
1310            }
1311        }
1312    }
1313
1314    #[inline]
1315    unsafe fn set_table<'w>(
1316        fetch: &mut RefFetch<'w, T>,
1317        &component_id: &ComponentId,
1318        table: &'w Table,
1319    ) {
1320        let column = table.get_column(component_id).debug_checked_unwrap();
1321        let table_data = Some((
1322            column.get_data_slice(table.entity_count()).into(),
1323            column.get_added_ticks_slice(table.entity_count()).into(),
1324            column.get_changed_ticks_slice(table.entity_count()).into(),
1325            #[cfg(feature = "track_change_detection")]
1326            column.get_changed_by_slice(table.entity_count()).into(),
1327            #[cfg(not(feature = "track_change_detection"))]
1328            (),
1329        ));
1330        // SAFETY: set_table is only called when T::STORAGE_TYPE = StorageType::Table
1331        unsafe { fetch.components.set_table(table_data) };
1332    }
1333
1334    #[inline(always)]
1335    unsafe fn fetch<'w>(
1336        fetch: &mut Self::Fetch<'w>,
1337        entity: Entity,
1338        table_row: TableRow,
1339    ) -> Self::Item<'w> {
1340        fetch.components.extract(
1341            |table| {
1342                // SAFETY: set_table was previously called
1343                let (table_components, added_ticks, changed_ticks, _callers) =
1344                    unsafe { table.debug_checked_unwrap() };
1345
1346                // SAFETY: The caller ensures `table_row` is in range.
1347                let component = unsafe { table_components.get(table_row.as_usize()) };
1348                // SAFETY: The caller ensures `table_row` is in range.
1349                let added = unsafe { added_ticks.get(table_row.as_usize()) };
1350                // SAFETY: The caller ensures `table_row` is in range.
1351                let changed = unsafe { changed_ticks.get(table_row.as_usize()) };
1352                // SAFETY: The caller ensures `table_row` is in range.
1353                #[cfg(feature = "track_change_detection")]
1354                let caller = unsafe { _callers.get(table_row.as_usize()) };
1355
1356                Ref {
1357                    value: component.deref(),
1358                    ticks: Ticks {
1359                        added: added.deref(),
1360                        changed: changed.deref(),
1361                        this_run: fetch.this_run,
1362                        last_run: fetch.last_run,
1363                    },
1364                    #[cfg(feature = "track_change_detection")]
1365                    changed_by: caller.deref(),
1366                }
1367            },
1368            |sparse_set| {
1369                // SAFETY: The caller ensures `entity` is in range.
1370                let (component, ticks, _caller) =
1371                    unsafe { sparse_set.get_with_ticks(entity).debug_checked_unwrap() };
1372
1373                Ref {
1374                    value: component.deref(),
1375                    ticks: Ticks::from_tick_cells(ticks, fetch.last_run, fetch.this_run),
1376                    #[cfg(feature = "track_change_detection")]
1377                    changed_by: _caller.deref(),
1378                }
1379            },
1380        )
1381    }
1382
1383    fn update_component_access(
1384        &component_id: &ComponentId,
1385        access: &mut FilteredAccess<ComponentId>,
1386    ) {
1387        assert!(
1388            !access.access().has_component_write(component_id),
1389            "&{} conflicts with a previous access in this query. Shared access cannot coincide with exclusive access.",
1390            core::any::type_name::<T>(),
1391        );
1392        access.add_component_read(component_id);
1393    }
1394
1395    fn init_state(world: &mut World) -> ComponentId {
1396        world.register_component::<T>()
1397    }
1398
1399    fn get_state(components: &Components) -> Option<Self::State> {
1400        components.component_id::<T>()
1401    }
1402
1403    fn matches_component_set(
1404        &state: &ComponentId,
1405        set_contains_id: &impl Fn(ComponentId) -> bool,
1406    ) -> bool {
1407        set_contains_id(state)
1408    }
1409}
1410
1411/// SAFETY: `Self` is the same as `Self::ReadOnly`
1412unsafe impl<'__w, T: Component> QueryData for Ref<'__w, T> {
1413    type ReadOnly = Self;
1414}
1415
1416/// SAFETY: access is read only
1417unsafe impl<'__w, T: Component> ReadOnlyQueryData for Ref<'__w, T> {}
1418
1419/// The [`WorldQuery::Fetch`] type for `&mut T`.
1420pub struct WriteFetch<'w, T: Component> {
1421    components: StorageSwitch<
1422        T,
1423        // T::STORAGE_TYPE = StorageType::Table
1424        Option<(
1425            ThinSlicePtr<'w, UnsafeCell<T>>,
1426            ThinSlicePtr<'w, UnsafeCell<Tick>>,
1427            ThinSlicePtr<'w, UnsafeCell<Tick>>,
1428            MaybeThinSlicePtrLocation<'w>,
1429        )>,
1430        // T::STORAGE_TYPE = StorageType::SparseSet
1431        &'w ComponentSparseSet,
1432    >,
1433    last_run: Tick,
1434    this_run: Tick,
1435}
1436
1437impl<T: Component> Clone for WriteFetch<'_, T> {
1438    fn clone(&self) -> Self {
1439        *self
1440    }
1441}
1442impl<T: Component> Copy for WriteFetch<'_, T> {}
1443
1444/// SAFETY:
1445/// `fetch` accesses a single component mutably.
1446/// This is sound because `update_component_access` and `update_archetype_component_access` add write access for that component and panic when appropriate.
1447/// `update_component_access` adds a `With` filter for a component.
1448/// This is sound because `matches_component_set` returns whether the set contains that component.
1449unsafe impl<'__w, T: Component> WorldQuery for &'__w mut T {
1450    type Item<'w> = Mut<'w, T>;
1451    type Fetch<'w> = WriteFetch<'w, T>;
1452    type State = ComponentId;
1453
1454    fn shrink<'wlong: 'wshort, 'wshort>(item: Mut<'wlong, T>) -> Mut<'wshort, T> {
1455        item
1456    }
1457
1458    fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {
1459        fetch
1460    }
1461
1462    #[inline]
1463    unsafe fn init_fetch<'w>(
1464        world: UnsafeWorldCell<'w>,
1465        &component_id: &ComponentId,
1466        last_run: Tick,
1467        this_run: Tick,
1468    ) -> WriteFetch<'w, T> {
1469        WriteFetch {
1470            components: StorageSwitch::new(
1471                || None,
1472                || {
1473                    // SAFETY: The underlying type associated with `component_id` is `T`,
1474                    // which we are allowed to access since we registered it in `update_archetype_component_access`.
1475                    // Note that we do not actually access any components in this function, we just get a shared
1476                    // reference to the sparse set, which is used to access the components in `Self::fetch`.
1477                    unsafe {
1478                        world
1479                            .storages()
1480                            .sparse_sets
1481                            .get(component_id)
1482                            .debug_checked_unwrap()
1483                    }
1484                },
1485            ),
1486            last_run,
1487            this_run,
1488        }
1489    }
1490
1491    const IS_DENSE: bool = {
1492        match T::STORAGE_TYPE {
1493            StorageType::Table => true,
1494            StorageType::SparseSet => false,
1495        }
1496    };
1497
1498    #[inline]
1499    unsafe fn set_archetype<'w>(
1500        fetch: &mut WriteFetch<'w, T>,
1501        component_id: &ComponentId,
1502        _archetype: &'w Archetype,
1503        table: &'w Table,
1504    ) {
1505        if Self::IS_DENSE {
1506            // SAFETY: `set_archetype`'s safety rules are a super set of the `set_table`'s ones.
1507            unsafe {
1508                Self::set_table(fetch, component_id, table);
1509            }
1510        }
1511    }
1512
1513    #[inline]
1514    unsafe fn set_table<'w>(
1515        fetch: &mut WriteFetch<'w, T>,
1516        &component_id: &ComponentId,
1517        table: &'w Table,
1518    ) {
1519        let column = table.get_column(component_id).debug_checked_unwrap();
1520        let table_data = Some((
1521            column.get_data_slice(table.entity_count()).into(),
1522            column.get_added_ticks_slice(table.entity_count()).into(),
1523            column.get_changed_ticks_slice(table.entity_count()).into(),
1524            #[cfg(feature = "track_change_detection")]
1525            column.get_changed_by_slice(table.entity_count()).into(),
1526            #[cfg(not(feature = "track_change_detection"))]
1527            (),
1528        ));
1529        // SAFETY: set_table is only called when T::STORAGE_TYPE = StorageType::Table
1530        unsafe { fetch.components.set_table(table_data) };
1531    }
1532
1533    #[inline(always)]
1534    unsafe fn fetch<'w>(
1535        fetch: &mut Self::Fetch<'w>,
1536        entity: Entity,
1537        table_row: TableRow,
1538    ) -> Self::Item<'w> {
1539        fetch.components.extract(
1540            |table| {
1541                // SAFETY: set_table was previously called
1542                let (table_components, added_ticks, changed_ticks, _callers) =
1543                    unsafe { table.debug_checked_unwrap() };
1544
1545                // SAFETY: The caller ensures `table_row` is in range.
1546                let component = unsafe { table_components.get(table_row.as_usize()) };
1547                // SAFETY: The caller ensures `table_row` is in range.
1548                let added = unsafe { added_ticks.get(table_row.as_usize()) };
1549                // SAFETY: The caller ensures `table_row` is in range.
1550                let changed = unsafe { changed_ticks.get(table_row.as_usize()) };
1551                // SAFETY: The caller ensures `table_row` is in range.
1552                #[cfg(feature = "track_change_detection")]
1553                let caller = unsafe { _callers.get(table_row.as_usize()) };
1554
1555                Mut {
1556                    value: component.deref_mut(),
1557                    ticks: TicksMut {
1558                        added: added.deref_mut(),
1559                        changed: changed.deref_mut(),
1560                        this_run: fetch.this_run,
1561                        last_run: fetch.last_run,
1562                    },
1563                    #[cfg(feature = "track_change_detection")]
1564                    changed_by: caller.deref_mut(),
1565                }
1566            },
1567            |sparse_set| {
1568                // SAFETY: The caller ensures `entity` is in range.
1569                let (component, ticks, _caller) =
1570                    unsafe { sparse_set.get_with_ticks(entity).debug_checked_unwrap() };
1571
1572                Mut {
1573                    value: component.assert_unique().deref_mut(),
1574                    ticks: TicksMut::from_tick_cells(ticks, fetch.last_run, fetch.this_run),
1575                    #[cfg(feature = "track_change_detection")]
1576                    changed_by: _caller.deref_mut(),
1577                }
1578            },
1579        )
1580    }
1581
1582    fn update_component_access(
1583        &component_id: &ComponentId,
1584        access: &mut FilteredAccess<ComponentId>,
1585    ) {
1586        assert!(
1587            !access.access().has_component_read(component_id),
1588            "&mut {} conflicts with a previous access in this query. Mutable component access must be unique.",
1589            core::any::type_name::<T>(),
1590        );
1591        access.add_component_write(component_id);
1592    }
1593
1594    fn init_state(world: &mut World) -> ComponentId {
1595        world.register_component::<T>()
1596    }
1597
1598    fn get_state(components: &Components) -> Option<Self::State> {
1599        components.component_id::<T>()
1600    }
1601
1602    fn matches_component_set(
1603        &state: &ComponentId,
1604        set_contains_id: &impl Fn(ComponentId) -> bool,
1605    ) -> bool {
1606        set_contains_id(state)
1607    }
1608}
1609
1610/// SAFETY: access of `&T` is a subset of `&mut T`
1611unsafe impl<'__w, T: Component> QueryData for &'__w mut T {
1612    type ReadOnly = &'__w T;
1613}
1614
1615/// When `Mut<T>` is used in a query, it will be converted to `Ref<T>` when transformed into its read-only form, providing access to change detection methods.
1616///
1617/// By contrast `&mut T` will result in a `Mut<T>` item in mutable form to record mutations, but result in a bare `&T` in read-only form.
1618///
1619/// SAFETY:
1620/// `fetch` accesses a single component mutably.
1621/// This is sound because `update_component_access` and `update_archetype_component_access` add write access for that component and panic when appropriate.
1622/// `update_component_access` adds a `With` filter for a component.
1623/// This is sound because `matches_component_set` returns whether the set contains that component.
1624unsafe impl<'__w, T: Component> WorldQuery for Mut<'__w, T> {
1625    type Item<'w> = Mut<'w, T>;
1626    type Fetch<'w> = WriteFetch<'w, T>;
1627    type State = ComponentId;
1628
1629    // Forwarded to `&mut T`
1630    fn shrink<'wlong: 'wshort, 'wshort>(item: Mut<'wlong, T>) -> Mut<'wshort, T> {
1631        <&mut T as WorldQuery>::shrink(item)
1632    }
1633
1634    fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {
1635        fetch
1636    }
1637
1638    #[inline]
1639    // Forwarded to `&mut T`
1640    unsafe fn init_fetch<'w>(
1641        world: UnsafeWorldCell<'w>,
1642        state: &ComponentId,
1643        last_run: Tick,
1644        this_run: Tick,
1645    ) -> WriteFetch<'w, T> {
1646        <&mut T as WorldQuery>::init_fetch(world, state, last_run, this_run)
1647    }
1648
1649    // Forwarded to `&mut T`
1650    const IS_DENSE: bool = <&mut T as WorldQuery>::IS_DENSE;
1651
1652    #[inline]
1653    // Forwarded to `&mut T`
1654    unsafe fn set_archetype<'w>(
1655        fetch: &mut WriteFetch<'w, T>,
1656        state: &ComponentId,
1657        archetype: &'w Archetype,
1658        table: &'w Table,
1659    ) {
1660        <&mut T as WorldQuery>::set_archetype(fetch, state, archetype, table);
1661    }
1662
1663    #[inline]
1664    // Forwarded to `&mut T`
1665    unsafe fn set_table<'w>(fetch: &mut WriteFetch<'w, T>, state: &ComponentId, table: &'w Table) {
1666        <&mut T as WorldQuery>::set_table(fetch, state, table);
1667    }
1668
1669    #[inline(always)]
1670    // Forwarded to `&mut T`
1671    unsafe fn fetch<'w>(
1672        // Rust complains about lifetime bounds not matching the trait if I directly use `WriteFetch<'w, T>` right here.
1673        // But it complains nowhere else in the entire trait implementation.
1674        fetch: &mut Self::Fetch<'w>,
1675        entity: Entity,
1676        table_row: TableRow,
1677    ) -> Mut<'w, T> {
1678        <&mut T as WorldQuery>::fetch(fetch, entity, table_row)
1679    }
1680
1681    // NOT forwarded to `&mut T`
1682    fn update_component_access(
1683        &component_id: &ComponentId,
1684        access: &mut FilteredAccess<ComponentId>,
1685    ) {
1686        // Update component access here instead of in `<&mut T as WorldQuery>` to avoid erroneously referencing
1687        // `&mut T` in error message.
1688        assert!(
1689            !access.access().has_component_read(component_id),
1690            "Mut<{}> conflicts with a previous access in this query. Mutable component access mut be unique.",
1691            core::any::type_name::<T>(),
1692        );
1693        access.add_component_write(component_id);
1694    }
1695
1696    // Forwarded to `&mut T`
1697    fn init_state(world: &mut World) -> ComponentId {
1698        <&mut T as WorldQuery>::init_state(world)
1699    }
1700
1701    // Forwarded to `&mut T`
1702    fn get_state(components: &Components) -> Option<ComponentId> {
1703        <&mut T as WorldQuery>::get_state(components)
1704    }
1705
1706    // Forwarded to `&mut T`
1707    fn matches_component_set(
1708        state: &ComponentId,
1709        set_contains_id: &impl Fn(ComponentId) -> bool,
1710    ) -> bool {
1711        <&mut T as WorldQuery>::matches_component_set(state, set_contains_id)
1712    }
1713}
1714
1715// SAFETY: access of `Ref<T>` is a subset of `Mut<T>`
1716unsafe impl<'__w, T: Component> QueryData for Mut<'__w, T> {
1717    type ReadOnly = Ref<'__w, T>;
1718}
1719
1720#[doc(hidden)]
1721pub struct OptionFetch<'w, T: WorldQuery> {
1722    fetch: T::Fetch<'w>,
1723    matches: bool,
1724}
1725
1726impl<T: WorldQuery> Clone for OptionFetch<'_, T> {
1727    fn clone(&self) -> Self {
1728        Self {
1729            fetch: self.fetch.clone(),
1730            matches: self.matches,
1731        }
1732    }
1733}
1734
1735/// SAFETY:
1736/// `fetch` might access any components that `T` accesses.
1737/// This is sound because `update_component_access` and `update_archetype_component_access` add the same accesses as `T`.
1738/// Filters are unchanged.
1739unsafe impl<T: WorldQuery> WorldQuery for Option<T> {
1740    type Item<'w> = Option<T::Item<'w>>;
1741    type Fetch<'w> = OptionFetch<'w, T>;
1742    type State = T::State;
1743
1744    fn shrink<'wlong: 'wshort, 'wshort>(item: Self::Item<'wlong>) -> Self::Item<'wshort> {
1745        item.map(T::shrink)
1746    }
1747
1748    fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {
1749        OptionFetch {
1750            fetch: T::shrink_fetch(fetch.fetch),
1751            matches: fetch.matches,
1752        }
1753    }
1754
1755    #[inline]
1756    unsafe fn init_fetch<'w>(
1757        world: UnsafeWorldCell<'w>,
1758        state: &T::State,
1759        last_run: Tick,
1760        this_run: Tick,
1761    ) -> OptionFetch<'w, T> {
1762        OptionFetch {
1763            // SAFETY: The invariants are uphold by the caller.
1764            fetch: unsafe { T::init_fetch(world, state, last_run, this_run) },
1765            matches: false,
1766        }
1767    }
1768
1769    const IS_DENSE: bool = T::IS_DENSE;
1770
1771    #[inline]
1772    unsafe fn set_archetype<'w>(
1773        fetch: &mut OptionFetch<'w, T>,
1774        state: &T::State,
1775        archetype: &'w Archetype,
1776        table: &'w Table,
1777    ) {
1778        fetch.matches = T::matches_component_set(state, &|id| archetype.contains(id));
1779        if fetch.matches {
1780            // SAFETY: The invariants are uphold by the caller.
1781            unsafe {
1782                T::set_archetype(&mut fetch.fetch, state, archetype, table);
1783            }
1784        }
1785    }
1786
1787    #[inline]
1788    unsafe fn set_table<'w>(fetch: &mut OptionFetch<'w, T>, state: &T::State, table: &'w Table) {
1789        fetch.matches = T::matches_component_set(state, &|id| table.has_column(id));
1790        if fetch.matches {
1791            // SAFETY: The invariants are uphold by the caller.
1792            unsafe {
1793                T::set_table(&mut fetch.fetch, state, table);
1794            }
1795        }
1796    }
1797
1798    #[inline(always)]
1799    unsafe fn fetch<'w>(
1800        fetch: &mut Self::Fetch<'w>,
1801        entity: Entity,
1802        table_row: TableRow,
1803    ) -> Self::Item<'w> {
1804        fetch
1805            .matches
1806            // SAFETY: The invariants are uphold by the caller.
1807            .then(|| unsafe { T::fetch(&mut fetch.fetch, entity, table_row) })
1808    }
1809
1810    fn update_component_access(state: &T::State, access: &mut FilteredAccess<ComponentId>) {
1811        // FilteredAccess::add_[write,read] adds the component to the `with` filter.
1812        // Those methods are called on `access` in `T::update_component_access`.
1813        // But in `Option<T>`, we specifically don't filter on `T`,
1814        // since `(Option<T>, &OtherComponent)` should be a valid item, even
1815        // if `Option<T>` is `None`.
1816        //
1817        // We pass a clone of the `FilteredAccess` to `T`, and only update the `Access`
1818        // using `extend_access` so that we can apply `T`'s component_access
1819        // without updating the `with` filters of `access`.
1820        let mut intermediate = access.clone();
1821        T::update_component_access(state, &mut intermediate);
1822        access.extend_access(&intermediate);
1823    }
1824
1825    fn init_state(world: &mut World) -> T::State {
1826        T::init_state(world)
1827    }
1828
1829    fn get_state(components: &Components) -> Option<Self::State> {
1830        T::get_state(components)
1831    }
1832
1833    fn matches_component_set(
1834        _state: &T::State,
1835        _set_contains_id: &impl Fn(ComponentId) -> bool,
1836    ) -> bool {
1837        true
1838    }
1839}
1840
1841// SAFETY: defers to soundness of `T: WorldQuery` impl
1842unsafe impl<T: QueryData> QueryData for Option<T> {
1843    type ReadOnly = Option<T::ReadOnly>;
1844}
1845
1846/// SAFETY: [`OptionFetch`] is read only because `T` is read only
1847unsafe impl<T: ReadOnlyQueryData> ReadOnlyQueryData for Option<T> {}
1848
1849/// Returns a bool that describes if an entity has the component `T`.
1850///
1851/// This can be used in a [`Query`](crate::system::Query) if you want to know whether or not entities
1852/// have the component `T`  but don't actually care about the component's value.
1853///
1854/// # Footguns
1855///
1856/// Note that a `Query<Has<T>>` will match all existing entities.
1857/// Beware! Even if it matches all entities, it doesn't mean that `query.get(entity)`
1858/// will always return `Ok(bool)`.
1859///
1860/// In the case of a non-existent entity, such as a despawned one, it will return `Err`.
1861/// A workaround is to replace `query.get(entity).unwrap()` by
1862/// `query.get(entity).unwrap_or_default()`.
1863///
1864/// # Examples
1865///
1866/// ```
1867/// # use bevy_ecs::component::Component;
1868/// # use bevy_ecs::query::Has;
1869/// # use bevy_ecs::system::IntoSystem;
1870/// # use bevy_ecs::system::Query;
1871/// #
1872/// # #[derive(Component)]
1873/// # struct IsHungry;
1874/// # #[derive(Component)]
1875/// # struct Name { name: &'static str };
1876/// #
1877/// fn food_entity_system(query: Query<(&Name, Has<IsHungry>) >) {
1878///     for (name, is_hungry) in &query {
1879///         if is_hungry{
1880///             println!("{} would like some food.", name.name);
1881///         } else {
1882///             println!("{} has had sufficient.", name.name);
1883///         }
1884///     }
1885/// }
1886/// # bevy_ecs::system::assert_is_system(food_entity_system);
1887/// ```
1888///
1889/// ```
1890/// # use bevy_ecs::component::Component;
1891/// # use bevy_ecs::query::Has;
1892/// # use bevy_ecs::system::IntoSystem;
1893/// # use bevy_ecs::system::Query;
1894/// #
1895/// # #[derive(Component)]
1896/// # struct Alpha{has_beta: bool};
1897/// # #[derive(Component)]
1898/// # struct Beta { has_alpha: bool };
1899/// #
1900/// // Unlike `Option<&T>`, `Has<T>` is compatible with `&mut T`
1901/// // as it does not actually access any data.
1902/// fn alphabet_entity_system(mut alphas: Query<(&mut Alpha, Has<Beta>)>, mut betas: Query<(&mut Beta, Has<Alpha>)>) {
1903///     for (mut alpha, has_beta) in alphas.iter_mut() {
1904///         alpha.has_beta = has_beta;
1905///     }
1906///     for (mut beta, has_alpha) in betas.iter_mut() {
1907///         beta.has_alpha = has_alpha;
1908///     }
1909/// }
1910/// # bevy_ecs::system::assert_is_system(alphabet_entity_system);
1911/// ```
1912pub struct Has<T>(PhantomData<T>);
1913
1914impl<T> core::fmt::Debug for Has<T> {
1915    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> {
1916        write!(f, "Has<{}>", core::any::type_name::<T>())
1917    }
1918}
1919
1920/// SAFETY:
1921/// `update_component_access` and `update_archetype_component_access` do nothing.
1922/// This is sound because `fetch` does not access components.
1923unsafe impl<T: Component> WorldQuery for Has<T> {
1924    type Item<'w> = bool;
1925    type Fetch<'w> = bool;
1926    type State = ComponentId;
1927
1928    fn shrink<'wlong: 'wshort, 'wshort>(item: Self::Item<'wlong>) -> Self::Item<'wshort> {
1929        item
1930    }
1931
1932    fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {
1933        fetch
1934    }
1935
1936    #[inline]
1937    unsafe fn init_fetch<'w>(
1938        _world: UnsafeWorldCell<'w>,
1939        _state: &Self::State,
1940        _last_run: Tick,
1941        _this_run: Tick,
1942    ) -> Self::Fetch<'w> {
1943        false
1944    }
1945
1946    const IS_DENSE: bool = {
1947        match T::STORAGE_TYPE {
1948            StorageType::Table => true,
1949            StorageType::SparseSet => false,
1950        }
1951    };
1952
1953    #[inline]
1954    unsafe fn set_archetype<'w>(
1955        fetch: &mut Self::Fetch<'w>,
1956        state: &Self::State,
1957        archetype: &'w Archetype,
1958        _table: &Table,
1959    ) {
1960        *fetch = archetype.contains(*state);
1961    }
1962
1963    #[inline]
1964    unsafe fn set_table<'w>(fetch: &mut Self::Fetch<'w>, state: &Self::State, table: &'w Table) {
1965        *fetch = table.has_column(*state);
1966    }
1967
1968    #[inline(always)]
1969    unsafe fn fetch<'w>(
1970        fetch: &mut Self::Fetch<'w>,
1971        _entity: Entity,
1972        _table_row: TableRow,
1973    ) -> Self::Item<'w> {
1974        *fetch
1975    }
1976
1977    fn update_component_access(
1978        &component_id: &Self::State,
1979        access: &mut FilteredAccess<ComponentId>,
1980    ) {
1981        access.access_mut().add_archetypal(component_id);
1982    }
1983
1984    fn init_state(world: &mut World) -> ComponentId {
1985        world.register_component::<T>()
1986    }
1987
1988    fn get_state(components: &Components) -> Option<Self::State> {
1989        components.component_id::<T>()
1990    }
1991
1992    fn matches_component_set(
1993        _state: &Self::State,
1994        _set_contains_id: &impl Fn(ComponentId) -> bool,
1995    ) -> bool {
1996        // `Has<T>` always matches
1997        true
1998    }
1999}
2000
2001/// SAFETY: `Self` is the same as `Self::ReadOnly`
2002unsafe impl<T: Component> QueryData for Has<T> {
2003    type ReadOnly = Self;
2004}
2005
2006/// SAFETY: [`Has`] is read only
2007unsafe impl<T: Component> ReadOnlyQueryData for Has<T> {}
2008
2009/// The `AnyOf` query parameter fetches entities with any of the component types included in T.
2010///
2011/// `Query<AnyOf<(&A, &B, &mut C)>>` is equivalent to `Query<(Option<&A>, Option<&B>, Option<&mut C>), Or<(With<A>, With<B>, With<C>)>>`.
2012/// Each of the components in `T` is returned as an `Option`, as with `Option<A>` queries.
2013/// Entities are guaranteed to have at least one of the components in `T`.
2014pub struct AnyOf<T>(PhantomData<T>);
2015
2016macro_rules! impl_tuple_query_data {
2017    ($(#[$meta:meta])* $(($name: ident, $state: ident)),*) => {
2018        #[allow(non_snake_case)]
2019        #[allow(clippy::unused_unit)]
2020        $(#[$meta])*
2021        // SAFETY: defers to soundness `$name: WorldQuery` impl
2022        unsafe impl<$($name: QueryData),*> QueryData for ($($name,)*) {
2023            type ReadOnly = ($($name::ReadOnly,)*);
2024        }
2025
2026        $(#[$meta])*
2027        /// SAFETY: each item in the tuple is read only
2028        unsafe impl<$($name: ReadOnlyQueryData),*> ReadOnlyQueryData for ($($name,)*) {}
2029
2030    };
2031}
2032
2033macro_rules! impl_anytuple_fetch {
2034    ($(#[$meta:meta])* $(($name: ident, $state: ident)),*) => {
2035        $(#[$meta])*
2036        #[allow(non_snake_case)]
2037        #[allow(clippy::unused_unit)]
2038        /// SAFETY:
2039        /// `fetch` accesses are a subset of the subqueries' accesses
2040        /// This is sound because `update_component_access` and `update_archetype_component_access` adds accesses according to the implementations of all the subqueries.
2041        /// `update_component_access` replaces the filters with a disjunction where every element is a conjunction of the previous filters and the filters of one of the subqueries.
2042        /// This is sound because `matches_component_set` returns a disjunction of the results of the subqueries' implementations.
2043        unsafe impl<$($name: WorldQuery),*> WorldQuery for AnyOf<($($name,)*)> {
2044            type Fetch<'w> = ($(($name::Fetch<'w>, bool),)*);
2045            type Item<'w> = ($(Option<$name::Item<'w>>,)*);
2046            type State = ($($name::State,)*);
2047
2048            fn shrink<'wlong: 'wshort, 'wshort>(item: Self::Item<'wlong>) -> Self::Item<'wshort> {
2049                let ($($name,)*) = item;
2050                ($(
2051                    $name.map($name::shrink),
2052                )*)
2053            }
2054            fn shrink_fetch<'wlong: 'wshort, 'wshort>(fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {
2055                let ($($name,)*) = fetch;
2056                ($(
2057                    ($name::shrink_fetch($name.0), $name.1),
2058                )*)
2059            }
2060
2061            #[inline]
2062            #[allow(clippy::unused_unit)]
2063            unsafe fn init_fetch<'w>(_world: UnsafeWorldCell<'w>, state: &Self::State, _last_run: Tick, _this_run: Tick) -> Self::Fetch<'w> {
2064                let ($($name,)*) = state;
2065                 // SAFETY: The invariants are uphold by the caller.
2066                ($(( unsafe { $name::init_fetch(_world, $name, _last_run, _this_run) }, false),)*)
2067            }
2068
2069            const IS_DENSE: bool = true $(&& $name::IS_DENSE)*;
2070
2071            #[inline]
2072            unsafe fn set_archetype<'w>(
2073                _fetch: &mut Self::Fetch<'w>,
2074                _state: &Self::State,
2075                _archetype: &'w Archetype,
2076                _table: &'w Table
2077            ) {
2078                let ($($name,)*) = _fetch;
2079                let ($($state,)*) = _state;
2080                $(
2081                    $name.1 = $name::matches_component_set($state, &|id| _archetype.contains(id));
2082                    if $name.1 {
2083                         // SAFETY: The invariants are uphold by the caller.
2084                        unsafe { $name::set_archetype(&mut $name.0, $state, _archetype, _table); }
2085                    }
2086                )*
2087            }
2088
2089            #[inline]
2090            unsafe fn set_table<'w>(_fetch: &mut Self::Fetch<'w>, _state: &Self::State, _table: &'w Table) {
2091                let ($($name,)*) = _fetch;
2092                let ($($state,)*) = _state;
2093                $(
2094                    $name.1 = $name::matches_component_set($state, &|id| _table.has_column(id));
2095                    if $name.1 {
2096                         // SAFETY: The invariants are required to be upheld by the caller.
2097                        unsafe { $name::set_table(&mut $name.0, $state, _table); }
2098                    }
2099                )*
2100            }
2101
2102            #[inline(always)]
2103            #[allow(clippy::unused_unit)]
2104            unsafe fn fetch<'w>(
2105                _fetch: &mut Self::Fetch<'w>,
2106                _entity: Entity,
2107                _table_row: TableRow
2108            ) -> Self::Item<'w> {
2109                let ($($name,)*) = _fetch;
2110                ($(
2111                    // SAFETY: The invariants are required to be upheld by the caller.
2112                    $name.1.then(|| unsafe { $name::fetch(&mut $name.0, _entity, _table_row) }),
2113                )*)
2114            }
2115
2116            fn update_component_access(state: &Self::State, access: &mut FilteredAccess<ComponentId>) {
2117                // update the filters (Or<(With<$name>,)>)
2118                let ($($name,)*) = state;
2119
2120                let mut _new_access = FilteredAccess::matches_nothing();
2121
2122                $(
2123                    // Create an intermediate because `access`'s value needs to be preserved
2124                    // for the next query data, and `_new_access` has to be modified only by `append_or` to it,
2125                    // which only updates the `filter_sets`, not the `access`.
2126                    let mut intermediate = access.clone();
2127                    $name::update_component_access($name, &mut intermediate);
2128                    _new_access.append_or(&intermediate);
2129                )*
2130
2131                // Of the accumulated `_new_access` we only care about the filter sets, not the access.
2132                access.filter_sets = _new_access.filter_sets;
2133
2134                // For the access we instead delegate to a tuple of `Option`s.
2135                // This has essentially the same semantics of `AnyOf`, except that it doesn't
2136                // require at least one of them to be `Some`.
2137                // We however solve this by setting explicitly the `filter_sets` above.
2138                // Also note that Option<T> updates the `access` but not the `filter_sets`.
2139                <($(Option<$name>,)*)>::update_component_access(state, access);
2140
2141            }
2142            #[allow(unused_variables)]
2143            fn init_state(world: &mut World) -> Self::State {
2144                ($($name::init_state(world),)*)
2145            }
2146            #[allow(unused_variables)]
2147            fn get_state(components: &Components) -> Option<Self::State> {
2148                Some(($($name::get_state(components)?,)*))
2149            }
2150
2151            fn matches_component_set(_state: &Self::State, _set_contains_id: &impl Fn(ComponentId) -> bool) -> bool {
2152                let ($($name,)*) = _state;
2153                false $(|| $name::matches_component_set($name, _set_contains_id))*
2154            }
2155        }
2156
2157        $(#[$meta])*
2158        #[allow(non_snake_case)]
2159        #[allow(clippy::unused_unit)]
2160        // SAFETY: defers to soundness of `$name: WorldQuery` impl
2161        unsafe impl<$($name: QueryData),*> QueryData for AnyOf<($($name,)*)> {
2162            type ReadOnly = AnyOf<($($name::ReadOnly,)*)>;
2163        }
2164
2165        $(#[$meta])*
2166        /// SAFETY: each item in the tuple is read only
2167        unsafe impl<$($name: ReadOnlyQueryData),*> ReadOnlyQueryData for AnyOf<($($name,)*)> {}
2168    };
2169}
2170
2171all_tuples!(
2172    #[doc(fake_variadic)]
2173    impl_tuple_query_data,
2174    0,
2175    15,
2176    F,
2177    S
2178);
2179all_tuples!(
2180    #[doc(fake_variadic)]
2181    impl_anytuple_fetch,
2182    0,
2183    15,
2184    F,
2185    S
2186);
2187
2188/// [`WorldQuery`] used to nullify queries by turning `Query<D>` into `Query<NopWorldQuery<D>>`
2189///
2190/// This will rarely be useful to consumers of `bevy_ecs`.
2191pub(crate) struct NopWorldQuery<D: QueryData>(PhantomData<D>);
2192
2193/// SAFETY:
2194/// `update_component_access` and `update_archetype_component_access` do nothing.
2195/// This is sound because `fetch` does not access components.
2196unsafe impl<D: QueryData> WorldQuery for NopWorldQuery<D> {
2197    type Item<'w> = ();
2198    type Fetch<'w> = ();
2199    type State = D::State;
2200
2201    fn shrink<'wlong: 'wshort, 'wshort>(_: ()) {}
2202
2203    fn shrink_fetch<'wlong: 'wshort, 'wshort>(_: ()) {}
2204
2205    #[inline(always)]
2206    unsafe fn init_fetch(
2207        _world: UnsafeWorldCell,
2208        _state: &D::State,
2209        _last_run: Tick,
2210        _this_run: Tick,
2211    ) {
2212    }
2213
2214    const IS_DENSE: bool = D::IS_DENSE;
2215
2216    #[inline(always)]
2217    unsafe fn set_archetype(
2218        _fetch: &mut (),
2219        _state: &D::State,
2220        _archetype: &Archetype,
2221        _tables: &Table,
2222    ) {
2223    }
2224
2225    #[inline(always)]
2226    unsafe fn set_table<'w>(_fetch: &mut (), _state: &D::State, _table: &Table) {}
2227
2228    #[inline(always)]
2229    unsafe fn fetch<'w>(
2230        _fetch: &mut Self::Fetch<'w>,
2231        _entity: Entity,
2232        _table_row: TableRow,
2233    ) -> Self::Item<'w> {
2234    }
2235
2236    fn update_component_access(_state: &D::State, _access: &mut FilteredAccess<ComponentId>) {}
2237
2238    fn init_state(world: &mut World) -> Self::State {
2239        D::init_state(world)
2240    }
2241
2242    fn get_state(components: &Components) -> Option<Self::State> {
2243        D::get_state(components)
2244    }
2245
2246    fn matches_component_set(
2247        state: &Self::State,
2248        set_contains_id: &impl Fn(ComponentId) -> bool,
2249    ) -> bool {
2250        D::matches_component_set(state, set_contains_id)
2251    }
2252}
2253
2254/// SAFETY: `Self::ReadOnly` is `Self`
2255unsafe impl<D: QueryData> QueryData for NopWorldQuery<D> {
2256    type ReadOnly = Self;
2257}
2258
2259/// SAFETY: `NopFetch` never accesses any data
2260unsafe impl<D: QueryData> ReadOnlyQueryData for NopWorldQuery<D> {}
2261
2262/// SAFETY:
2263/// `update_component_access` and `update_archetype_component_access` do nothing.
2264/// This is sound because `fetch` does not access components.
2265unsafe impl<T: ?Sized> WorldQuery for PhantomData<T> {
2266    type Item<'a> = ();
2267    type Fetch<'a> = ();
2268
2269    type State = ();
2270
2271    fn shrink<'wlong: 'wshort, 'wshort>(_item: Self::Item<'wlong>) -> Self::Item<'wshort> {}
2272
2273    fn shrink_fetch<'wlong: 'wshort, 'wshort>(_fetch: Self::Fetch<'wlong>) -> Self::Fetch<'wshort> {
2274    }
2275
2276    unsafe fn init_fetch<'w>(
2277        _world: UnsafeWorldCell<'w>,
2278        _state: &Self::State,
2279        _last_run: Tick,
2280        _this_run: Tick,
2281    ) -> Self::Fetch<'w> {
2282    }
2283
2284    // `PhantomData` does not match any components, so all components it matches
2285    // are stored in a Table (vacuous truth).
2286    const IS_DENSE: bool = true;
2287
2288    unsafe fn set_archetype<'w>(
2289        _fetch: &mut Self::Fetch<'w>,
2290        _state: &Self::State,
2291        _archetype: &'w Archetype,
2292        _table: &'w Table,
2293    ) {
2294    }
2295
2296    unsafe fn set_table<'w>(_fetch: &mut Self::Fetch<'w>, _state: &Self::State, _table: &'w Table) {
2297    }
2298
2299    unsafe fn fetch<'w>(
2300        _fetch: &mut Self::Fetch<'w>,
2301        _entity: Entity,
2302        _table_row: TableRow,
2303    ) -> Self::Item<'w> {
2304    }
2305
2306    fn update_component_access(_state: &Self::State, _access: &mut FilteredAccess<ComponentId>) {}
2307
2308    fn init_state(_world: &mut World) -> Self::State {}
2309
2310    fn get_state(_components: &Components) -> Option<Self::State> {
2311        Some(())
2312    }
2313
2314    fn matches_component_set(
2315        _state: &Self::State,
2316        _set_contains_id: &impl Fn(ComponentId) -> bool,
2317    ) -> bool {
2318        true
2319    }
2320}
2321
2322/// SAFETY: `Self::ReadOnly` is `Self`
2323unsafe impl<T: ?Sized> QueryData for PhantomData<T> {
2324    type ReadOnly = Self;
2325}
2326
2327/// SAFETY: `PhantomData` never accesses any world data.
2328unsafe impl<T: ?Sized> ReadOnlyQueryData for PhantomData<T> {}
2329
2330/// A compile-time checked union of two different types that differs based on the
2331/// [`StorageType`] of a given component.
2332pub(super) union StorageSwitch<C: Component, T: Copy, S: Copy> {
2333    /// The table variant. Requires the component to be a table component.
2334    table: T,
2335    /// The sparse set variant. Requires the component to be a sparse set component.
2336    sparse_set: S,
2337    _marker: PhantomData<C>,
2338}
2339
2340impl<C: Component, T: Copy, S: Copy> StorageSwitch<C, T, S> {
2341    /// Creates a new [`StorageSwitch`] using the given closures to initialize
2342    /// the variant corresponding to the component's [`StorageType`].
2343    pub fn new(table: impl FnOnce() -> T, sparse_set: impl FnOnce() -> S) -> Self {
2344        match C::STORAGE_TYPE {
2345            StorageType::Table => Self { table: table() },
2346            StorageType::SparseSet => Self {
2347                sparse_set: sparse_set(),
2348            },
2349        }
2350    }
2351
2352    /// Creates a new [`StorageSwitch`] using a table variant.
2353    ///
2354    /// # Panics
2355    ///
2356    /// This will panic on debug builds if `C` is not a table component.
2357    ///
2358    /// # Safety
2359    ///
2360    /// `C` must be a table component.
2361    #[inline]
2362    pub unsafe fn set_table(&mut self, table: T) {
2363        match C::STORAGE_TYPE {
2364            StorageType::Table => self.table = table,
2365            _ => {
2366                #[cfg(debug_assertions)]
2367                unreachable!();
2368                #[cfg(not(debug_assertions))]
2369                std::hint::unreachable_unchecked()
2370            }
2371        }
2372    }
2373
2374    /// Fetches the internal value from the variant that corresponds to the
2375    /// component's [`StorageType`].
2376    pub fn extract<R>(&self, table: impl FnOnce(T) -> R, sparse_set: impl FnOnce(S) -> R) -> R {
2377        match C::STORAGE_TYPE {
2378            StorageType::Table => table(
2379                // SAFETY: C::STORAGE_TYPE == StorageType::Table
2380                unsafe { self.table },
2381            ),
2382            StorageType::SparseSet => sparse_set(
2383                // SAFETY: C::STORAGE_TYPE == StorageType::SparseSet
2384                unsafe { self.sparse_set },
2385            ),
2386        }
2387    }
2388}
2389
2390impl<C: Component, T: Copy, S: Copy> Clone for StorageSwitch<C, T, S> {
2391    fn clone(&self) -> Self {
2392        *self
2393    }
2394}
2395
2396impl<C: Component, T: Copy, S: Copy> Copy for StorageSwitch<C, T, S> {}
2397
2398#[cfg(test)]
2399mod tests {
2400    use bevy_ecs_macros::QueryData;
2401
2402    use super::*;
2403    use crate::{
2404        self as bevy_ecs,
2405        system::{assert_is_system, Query},
2406    };
2407
2408    #[derive(Component)]
2409    pub struct A;
2410
2411    #[derive(Component)]
2412    pub struct B;
2413
2414    // Tests that each variant of struct can be used as a `WorldQuery`.
2415    #[test]
2416    fn world_query_struct_variants() {
2417        #[derive(QueryData)]
2418        pub struct NamedQuery {
2419            id: Entity,
2420            a: &'static A,
2421        }
2422
2423        #[derive(QueryData)]
2424        pub struct TupleQuery(&'static A, &'static B);
2425
2426        #[derive(QueryData)]
2427        pub struct UnitQuery;
2428
2429        fn my_system(_: Query<(NamedQuery, TupleQuery, UnitQuery)>) {}
2430
2431        assert_is_system(my_system);
2432    }
2433
2434    // Compile test for https://github.com/bevyengine/bevy/pull/8030.
2435    #[test]
2436    fn world_query_phantom_data() {
2437        #[derive(QueryData)]
2438        pub struct IgnoredQuery<Marker> {
2439            id: Entity,
2440            _marker: PhantomData<Marker>,
2441        }
2442
2443        fn ignored_system(_: Query<IgnoredQuery<()>>) {}
2444
2445        assert_is_system(ignored_system);
2446    }
2447
2448    // Ensures that each field of a `WorldQuery` struct's read-only variant
2449    // has the same visibility as its corresponding mutable field.
2450    #[test]
2451    fn read_only_field_visibility() {
2452        mod private {
2453            use super::*;
2454
2455            #[derive(QueryData)]
2456            #[query_data(mutable)]
2457            pub struct D {
2458                pub a: &'static mut A,
2459            }
2460        }
2461
2462        let _ = private::DReadOnly { a: &A };
2463
2464        fn my_system(query: Query<private::D>) {
2465            for q in &query {
2466                let _ = &q.a;
2467            }
2468        }
2469
2470        assert_is_system(my_system);
2471    }
2472
2473    // Ensures that metadata types generated by the WorldQuery macro
2474    // do not conflict with user-defined types.
2475    // Regression test for https://github.com/bevyengine/bevy/issues/8010.
2476    #[test]
2477    fn world_query_metadata_collision() {
2478        // The metadata types generated would be named `ClientState` and `ClientFetch`,
2479        // but they should rename themselves to avoid conflicts.
2480        #[derive(QueryData)]
2481        pub struct Client<S: ClientState> {
2482            pub state: &'static S,
2483            pub fetch: &'static ClientFetch,
2484        }
2485
2486        pub trait ClientState: Component {}
2487
2488        #[derive(Component)]
2489        pub struct ClientFetch;
2490
2491        #[derive(Component)]
2492        pub struct C;
2493
2494        impl ClientState for C {}
2495
2496        fn client_system(_: Query<Client<C>>) {}
2497
2498        assert_is_system(client_system);
2499    }
2500}