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