Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/crates/bevy_ecs/src/entity_disabling.rs
9366 views
1
//! Disabled entities do not show up in queries unless the query explicitly mentions them.
2
//!
3
//! Entities which are disabled in this way are not removed from the [`World`],
4
//! and their relationships remain intact.
5
//! In many cases, you may want to disable entire trees of entities at once,
6
//! using [`EntityCommands::insert_recursive`](crate::prelude::EntityCommands::insert_recursive).
7
//!
8
//! While Bevy ships with a built-in [`Disabled`] component, you can also create your own
9
//! disabling components, which will operate in the same way but can have distinct semantics.
10
//!
11
//! ```
12
//! use bevy_ecs::prelude::*;
13
//!
14
//! // Our custom disabling component!
15
//! #[derive(Component, Clone)]
16
//! struct Prefab;
17
//!
18
//! #[derive(Component)]
19
//! struct A;
20
//!
21
//! let mut world = World::new();
22
//! world.register_disabling_component::<Prefab>();
23
//! world.spawn((A, Prefab));
24
//! world.spawn((A,));
25
//! world.spawn((A,));
26
//!
27
//! let mut normal_query = world.query::<&A>();
28
//! assert_eq!(2, normal_query.iter(&world).count());
29
//!
30
//! let mut prefab_query = world.query_filtered::<&A, With<Prefab>>();
31
//! assert_eq!(1, prefab_query.iter(&world).count());
32
//!
33
//! let mut maybe_prefab_query = world.query::<(&A, Has<Prefab>)>();
34
//! assert_eq!(3, maybe_prefab_query.iter(&world).count());
35
//! ```
36
//!
37
//! ## Default query filters
38
//!
39
//! In Bevy, entity disabling is implemented through the construction of a global "default query filter" resource.
40
//! Queries which do not explicitly mention the disabled component will not include entities with that component.
41
//! If an entity has multiple disabling components, it will only be included in queries that mention all of them.
42
//!
43
//! For example, `Query<&Position>` will not include entities with the [`Disabled`] component,
44
//! even if they have a `Position` component,
45
//! but `Query<&Position, With<Disabled>>` or `Query<(&Position, Has<Disabled>)>` will see them.
46
//!
47
//! The [`Allow`](crate::query::Allow) query filter is designed to be used with default query filters,
48
//! and ensures that the query will include entities both with and without the specified disabling component.
49
//!
50
//! Entities with disabling components are still present in the [`World`] and can be accessed directly,
51
//! using methods on [`World`] or [`Commands`](crate::prelude::Commands).
52
//!
53
//! As default query filters are implemented through a resource,
54
//! it's possible to temporarily ignore any default filters by using [`World::resource_scope`](crate::prelude::World).
55
//!
56
//! ```
57
//! use bevy_ecs::prelude::*;
58
//! use bevy_ecs::entity_disabling::{DefaultQueryFilters, Disabled};
59
//!
60
//! let mut world = World::default();
61
//!
62
//! #[derive(Component)]
63
//! struct CustomDisabled;
64
//!
65
//! world.register_disabling_component::<CustomDisabled>();
66
//!
67
//! world.spawn(Disabled);
68
//! world.spawn(CustomDisabled);
69
//!
70
//! // resource_scope removes DefaultQueryFilters temporarily before re-inserting into the world.
71
//! world.resource_scope(|world: &mut World, _: Mut<DefaultQueryFilters>| {
72
//! // within this scope, we can query like no components are disabled.
73
//! assert_eq!(world.query::<&Disabled>().query(&world).count(), 1);
74
//! assert_eq!(world.query::<&CustomDisabled>().query(&world).count(), 1);
75
//! assert_eq!(world.query::<()>().query(&world).count(), world.entities().count_spawned() as usize);
76
//! })
77
//! ```
78
//!
79
//! ### Warnings
80
//!
81
//! Currently, only queries for which the cache is built after enabling a default query filter will have entities
82
//! with those components filtered. As a result, they should generally only be modified before the
83
//! app starts.
84
//!
85
//! Because filters are applied to all queries they can have performance implication for
86
//! the entire [`World`], especially when they cause queries to mix sparse and table components.
87
//! See [`Query` performance] for more info.
88
//!
89
//! Custom disabling components can cause significant interoperability issues within the ecosystem,
90
//! as users must be aware of each disabling component in use.
91
//! Libraries should think carefully about whether they need to use a new disabling component,
92
//! and clearly communicate their presence to their users to avoid the new for library compatibility flags.
93
//!
94
//! [`With`]: crate::prelude::With
95
//! [`Has`]: crate::prelude::Has
96
//! [`World`]: crate::prelude::World
97
//! [`Query` performance]: crate::prelude::Query#performance
98
99
use crate::{
100
component::{ComponentId, Components, StorageType},
101
query::FilteredAccess,
102
world::{FromWorld, World},
103
};
104
use bevy_ecs_macros::{Component, Resource};
105
use smallvec::SmallVec;
106
107
#[cfg(feature = "bevy_reflect")]
108
use {
109
crate::reflect::{ReflectComponent, ReflectResource},
110
bevy_reflect::std_traits::ReflectDefault,
111
bevy_reflect::Reflect,
112
};
113
114
/// A marker component for disabled entities.
115
///
116
/// Semantically, this component is used to mark entities that are temporarily disabled (typically for gameplay reasons),
117
/// but will likely be re-enabled at some point.
118
///
119
/// Like all disabling components, this only disables the entity itself,
120
/// not its children or other entities that reference it.
121
/// To disable an entire tree of entities, use [`EntityCommands::insert_recursive`](crate::prelude::EntityCommands::insert_recursive).
122
///
123
/// Every [`World`] has a default query filter that excludes entities with this component,
124
/// registered in the [`DefaultQueryFilters`] resource.
125
/// See [the module docs] for more info.
126
///
127
/// [the module docs]: crate::entity_disabling
128
#[derive(Component, Clone, Debug, Default)]
129
#[cfg_attr(
130
feature = "bevy_reflect",
131
derive(Reflect),
132
reflect(Component),
133
reflect(Debug, Clone, Default)
134
)]
135
// This component is registered as a disabling component during World::bootstrap
136
pub struct Disabled;
137
138
/// Default query filters work by excluding entities with certain components from most queries.
139
///
140
/// If a query does not explicitly mention a given disabling component, it will not include entities with that component.
141
/// To be more precise, this checks if the query's [`FilteredAccess`] contains the component,
142
/// and if it does not, adds a [`Without`](crate::prelude::Without) filter for that component to the query.
143
///
144
/// [`Allow`](crate::query::Allow) and [`Has`](crate::prelude::Has) can be used to include entities
145
/// with and without the disabling component.
146
/// [`Allow`](crate::query::Allow) is a [`QueryFilter`](crate::query::QueryFilter) and will simply change
147
/// the list of shown entities, while [`Has`](crate::prelude::Has) is a [`QueryData`](crate::query::QueryData)
148
/// and will allow you to see if each entity has the disabling component or not.
149
///
150
/// This resource is initialized in the [`World`] whenever a new world is created,
151
/// with the [`Disabled`] component as a disabling component.
152
///
153
/// Note that you can remove default query filters by overwriting the [`DefaultQueryFilters`] resource.
154
/// This can be useful as a last resort escape hatch, but is liable to break compatibility with other libraries.
155
///
156
/// See the [module docs](crate::entity_disabling) for more info.
157
///
158
///
159
/// # Warning
160
///
161
/// Default query filters are a global setting that affects all queries in the [`World`],
162
/// and incur a small performance cost for each query.
163
///
164
/// They can cause significant interoperability issues within the ecosystem,
165
/// as users must be aware of each disabling component in use.
166
///
167
/// Think carefully about whether you need to use a new disabling component,
168
/// and clearly communicate their presence in any libraries you publish.
169
#[derive(Resource, Debug)]
170
#[cfg_attr(
171
feature = "bevy_reflect",
172
derive(bevy_reflect::Reflect),
173
reflect(Resource)
174
)]
175
pub struct DefaultQueryFilters {
176
// We only expect a few components per application to act as disabling components, so we use a SmallVec here
177
// to avoid heap allocation in most cases.
178
disabling: SmallVec<[ComponentId; 4]>,
179
}
180
181
impl FromWorld for DefaultQueryFilters {
182
fn from_world(world: &mut World) -> Self {
183
let mut filters = DefaultQueryFilters::empty();
184
let disabled_component_id = world.register_component::<Disabled>();
185
filters.register_disabling_component(disabled_component_id);
186
filters
187
}
188
}
189
190
impl DefaultQueryFilters {
191
/// Creates a new, completely empty [`DefaultQueryFilters`].
192
///
193
/// This is provided as an escape hatch; in most cases you should initialize this using [`FromWorld`],
194
/// which is automatically called when creating a new [`World`].
195
#[must_use]
196
pub fn empty() -> Self {
197
DefaultQueryFilters {
198
disabling: SmallVec::new(),
199
}
200
}
201
202
/// Adds this [`ComponentId`] to the set of [`DefaultQueryFilters`],
203
/// causing entities with this component to be excluded from queries.
204
///
205
/// This method is idempotent, and will not add the same component multiple times.
206
///
207
/// # Warning
208
///
209
/// This method should only be called before the app starts, as it will not affect queries
210
/// initialized before it is called.
211
///
212
/// As discussed in the [module docs](crate::entity_disabling), this can have performance implications,
213
/// as well as create interoperability issues, and should be used with caution.
214
pub fn register_disabling_component(&mut self, component_id: ComponentId) {
215
if !self.disabling.contains(&component_id) {
216
self.disabling.push(component_id);
217
}
218
}
219
220
/// Get an iterator over all of the components which disable entities when present.
221
pub fn disabling_ids(&self) -> impl Iterator<Item = ComponentId> {
222
self.disabling.iter().copied()
223
}
224
225
/// Modifies the provided [`FilteredAccess`] to include the filters from this [`DefaultQueryFilters`].
226
pub(super) fn modify_access(&self, component_access: &mut FilteredAccess) {
227
for component_id in self.disabling_ids() {
228
if !component_access.contains(component_id) {
229
component_access.and_without(component_id);
230
}
231
}
232
}
233
234
pub(super) fn is_dense(&self, components: &Components) -> bool {
235
self.disabling_ids().all(|component_id| {
236
components
237
.get_info(component_id)
238
.is_some_and(|info| info.storage_type() == StorageType::Table)
239
})
240
}
241
}
242
243
#[cfg(test)]
244
mod tests {
245
246
use super::*;
247
use crate::{
248
prelude::{EntityMut, EntityRef, World},
249
query::{Has, With},
250
};
251
use alloc::{vec, vec::Vec};
252
253
#[test]
254
fn filters_modify_access() {
255
let mut filters = DefaultQueryFilters::empty();
256
filters.register_disabling_component(ComponentId::new(1));
257
258
// A component access with an unrelated component
259
let mut component_access = FilteredAccess::default();
260
component_access
261
.access_mut()
262
.add_component_read(ComponentId::new(2));
263
264
let mut applied_access = component_access.clone();
265
filters.modify_access(&mut applied_access);
266
assert_eq!(0, applied_access.with_filters().count());
267
assert_eq!(
268
vec![ComponentId::new(1)],
269
applied_access.without_filters().collect::<Vec<_>>()
270
);
271
272
// We add a with filter, now we expect to see both filters
273
component_access.and_with(ComponentId::new(4));
274
275
let mut applied_access = component_access.clone();
276
filters.modify_access(&mut applied_access);
277
assert_eq!(
278
vec![ComponentId::new(4)],
279
applied_access.with_filters().collect::<Vec<_>>()
280
);
281
assert_eq!(
282
vec![ComponentId::new(1)],
283
applied_access.without_filters().collect::<Vec<_>>()
284
);
285
286
let copy = component_access.clone();
287
// We add a rule targeting a default component, that filter should no longer be added
288
component_access.and_with(ComponentId::new(1));
289
290
let mut applied_access = component_access.clone();
291
filters.modify_access(&mut applied_access);
292
assert_eq!(
293
vec![ComponentId::new(1), ComponentId::new(4)],
294
applied_access.with_filters().collect::<Vec<_>>()
295
);
296
assert_eq!(0, applied_access.without_filters().count());
297
298
// Archetypal access should also filter rules
299
component_access = copy.clone();
300
component_access
301
.access_mut()
302
.add_archetypal(ComponentId::new(1));
303
304
let mut applied_access = component_access.clone();
305
filters.modify_access(&mut applied_access);
306
assert_eq!(
307
vec![ComponentId::new(4)],
308
applied_access.with_filters().collect::<Vec<_>>()
309
);
310
assert_eq!(0, applied_access.without_filters().count());
311
}
312
313
#[derive(Component)]
314
struct CustomDisabled;
315
316
#[derive(Component)]
317
struct Dummy;
318
319
#[test]
320
fn multiple_disabling_components() {
321
let mut world = World::new();
322
world.register_disabling_component::<CustomDisabled>();
323
324
// Use powers of two so we can uniquely identify the set of matching archetypes from the count.
325
world.spawn(Dummy);
326
world.spawn_batch((0..2).map(|_| (Dummy, Disabled)));
327
world.spawn_batch((0..4).map(|_| (Dummy, CustomDisabled)));
328
world.spawn_batch((0..8).map(|_| (Dummy, Disabled, CustomDisabled)));
329
330
let mut query = world.query::<&Dummy>();
331
assert_eq!(1, query.iter(&world).count());
332
333
let mut query = world.query_filtered::<EntityRef, With<Dummy>>();
334
assert_eq!(1, query.iter(&world).count());
335
336
let mut query = world.query_filtered::<EntityMut, With<Dummy>>();
337
assert_eq!(1, query.iter(&world).count());
338
339
let mut query = world.query_filtered::<&Dummy, With<Disabled>>();
340
assert_eq!(2, query.iter(&world).count());
341
342
let mut query = world.query_filtered::<Has<Disabled>, With<Dummy>>();
343
assert_eq!(3, query.iter(&world).count());
344
345
let mut query = world.query_filtered::<&Dummy, With<CustomDisabled>>();
346
assert_eq!(4, query.iter(&world).count());
347
348
let mut query = world.query_filtered::<Has<CustomDisabled>, With<Dummy>>();
349
assert_eq!(5, query.iter(&world).count());
350
351
let mut query = world.query_filtered::<&Dummy, (With<Disabled>, With<CustomDisabled>)>();
352
assert_eq!(8, query.iter(&world).count());
353
354
let mut query = world.query_filtered::<(Has<Disabled>, Has<CustomDisabled>), With<Dummy>>();
355
assert_eq!(15, query.iter(&world).count());
356
357
// This seems like it ought to count as a mention of `Disabled`, but it does not.
358
// We don't consider read access, since that would count `EntityRef` as a mention of *all* components.
359
let mut query = world.query_filtered::<Option<&Disabled>, With<Dummy>>();
360
assert_eq!(1, query.iter(&world).count());
361
}
362
}
363
364