bevy_ecs/component.rs
1//! Types for declaring and storing [`Component`]s.
2
3use crate::{
4 archetype::ArchetypeFlags,
5 bundle::BundleInfo,
6 change_detection::{MaybeLocation, MAX_CHANGE_AGE},
7 entity::{ComponentCloneCtx, Entity, EntityMapper, SourceComponent},
8 query::DebugCheckedUnwrap,
9 relationship::RelationshipHookMode,
10 resource::Resource,
11 storage::{SparseSetIndex, SparseSets, Table, TableRow},
12 system::{Local, SystemParam},
13 world::{DeferredWorld, FromWorld, World},
14};
15use alloc::boxed::Box;
16use alloc::{borrow::Cow, format, vec::Vec};
17pub use bevy_ecs_macros::Component;
18use bevy_platform_support::sync::Arc;
19use bevy_platform_support::{
20 collections::{HashMap, HashSet},
21 sync::PoisonError,
22};
23use bevy_ptr::{OwningPtr, UnsafeCellDeref};
24#[cfg(feature = "bevy_reflect")]
25use bevy_reflect::Reflect;
26use bevy_utils::TypeIdMap;
27use core::{
28 alloc::Layout,
29 any::{Any, TypeId},
30 cell::UnsafeCell,
31 fmt::Debug,
32 marker::PhantomData,
33 mem::needs_drop,
34 ops::{Deref, DerefMut},
35};
36use disqualified::ShortName;
37use smallvec::SmallVec;
38use thiserror::Error;
39
40/// A data type that can be used to store data for an [entity].
41///
42/// `Component` is a [derivable trait]: this means that a data type can implement it by applying a `#[derive(Component)]` attribute to it.
43/// However, components must always satisfy the `Send + Sync + 'static` trait bounds.
44///
45/// [entity]: crate::entity
46/// [derivable trait]: https://doc.rust-lang.org/book/appendix-03-derivable-traits.html
47///
48/// # Examples
49///
50/// Components can take many forms: they are usually structs, but can also be of every other kind of data type, like enums or zero sized types.
51/// The following examples show how components are laid out in code.
52///
53/// ```
54/// # use bevy_ecs::component::Component;
55/// # struct Color;
56/// #
57/// // A component can contain data...
58/// #[derive(Component)]
59/// struct LicensePlate(String);
60///
61/// // ... but it can also be a zero-sized marker.
62/// #[derive(Component)]
63/// struct Car;
64///
65/// // Components can also be structs with named fields...
66/// #[derive(Component)]
67/// struct VehiclePerformance {
68/// acceleration: f32,
69/// top_speed: f32,
70/// handling: f32,
71/// }
72///
73/// // ... or enums.
74/// #[derive(Component)]
75/// enum WheelCount {
76/// Two,
77/// Three,
78/// Four,
79/// }
80/// ```
81///
82/// # Component and data access
83///
84/// Components can be marked as immutable by adding the `#[component(immutable)]`
85/// attribute when using the derive macro.
86/// See the documentation for [`ComponentMutability`] for more details around this
87/// feature.
88///
89/// See the [`entity`] module level documentation to learn how to add or remove components from an entity.
90///
91/// See the documentation for [`Query`] to learn how to access component data from a system.
92///
93/// [`entity`]: crate::entity#usage
94/// [`Query`]: crate::system::Query
95/// [`ComponentMutability`]: crate::component::ComponentMutability
96///
97/// # Choosing a storage type
98///
99/// Components can be stored in the world using different strategies with their own performance implications.
100/// By default, components are added to the [`Table`] storage, which is optimized for query iteration.
101///
102/// Alternatively, components can be added to the [`SparseSet`] storage, which is optimized for component insertion and removal.
103/// This is achieved by adding an additional `#[component(storage = "SparseSet")]` attribute to the derive one:
104///
105/// ```
106/// # use bevy_ecs::component::Component;
107/// #
108/// #[derive(Component)]
109/// #[component(storage = "SparseSet")]
110/// struct ComponentA;
111/// ```
112///
113/// [`Table`]: crate::storage::Table
114/// [`SparseSet`]: crate::storage::SparseSet
115///
116/// # Required Components
117///
118/// Components can specify Required Components. If some [`Component`] `A` requires [`Component`] `B`, then when `A` is inserted,
119/// `B` will _also_ be initialized and inserted (if it was not manually specified).
120///
121/// The [`Default`] constructor will be used to initialize the component, by default:
122///
123/// ```
124/// # use bevy_ecs::prelude::*;
125/// #[derive(Component)]
126/// #[require(B)]
127/// struct A;
128///
129/// #[derive(Component, Default, PartialEq, Eq, Debug)]
130/// struct B(usize);
131///
132/// # let mut world = World::default();
133/// // This will implicitly also insert B with the Default constructor
134/// let id = world.spawn(A).id();
135/// assert_eq!(&B(0), world.entity(id).get::<B>().unwrap());
136///
137/// // This will _not_ implicitly insert B, because it was already provided
138/// world.spawn((A, B(11)));
139/// ```
140///
141/// Components can have more than one required component:
142///
143/// ```
144/// # use bevy_ecs::prelude::*;
145/// #[derive(Component)]
146/// #[require(B, C)]
147/// struct A;
148///
149/// #[derive(Component, Default, PartialEq, Eq, Debug)]
150/// #[require(C)]
151/// struct B(usize);
152///
153/// #[derive(Component, Default, PartialEq, Eq, Debug)]
154/// struct C(u32);
155///
156/// # let mut world = World::default();
157/// // This will implicitly also insert B and C with their Default constructors
158/// let id = world.spawn(A).id();
159/// assert_eq!(&B(0), world.entity(id).get::<B>().unwrap());
160/// assert_eq!(&C(0), world.entity(id).get::<C>().unwrap());
161/// ```
162///
163/// You can define inline component values that take the following forms:
164/// ```
165/// # use bevy_ecs::prelude::*;
166/// #[derive(Component)]
167/// #[require(
168/// B(1), // tuple structs
169/// C { // named-field structs
170/// x: 1,
171/// ..Default::default()
172/// },
173/// D::One, // enum variants
174/// E::ONE, // associated consts
175/// F::new(1) // constructors
176/// )]
177/// struct A;
178///
179/// #[derive(Component, PartialEq, Eq, Debug)]
180/// struct B(u8);
181///
182/// #[derive(Component, PartialEq, Eq, Debug, Default)]
183/// struct C {
184/// x: u8,
185/// y: u8,
186/// }
187///
188/// #[derive(Component, PartialEq, Eq, Debug)]
189/// enum D {
190/// Zero,
191/// One,
192/// }
193///
194/// #[derive(Component, PartialEq, Eq, Debug)]
195/// struct E(u8);
196///
197/// impl E {
198/// pub const ONE: Self = Self(1);
199/// }
200///
201/// #[derive(Component, PartialEq, Eq, Debug)]
202/// struct F(u8);
203///
204/// impl F {
205/// fn new(value: u8) -> Self {
206/// Self(value)
207/// }
208/// }
209///
210/// # let mut world = World::default();
211/// let id = world.spawn(A).id();
212/// assert_eq!(&B(1), world.entity(id).get::<B>().unwrap());
213/// assert_eq!(&C { x: 1, y: 0 }, world.entity(id).get::<C>().unwrap());
214/// assert_eq!(&D::One, world.entity(id).get::<D>().unwrap());
215/// assert_eq!(&E(1), world.entity(id).get::<E>().unwrap());
216/// assert_eq!(&F(1), world.entity(id).get::<F>().unwrap());
217/// ````
218///
219///
220/// You can also define arbitrary expressions by using `=`
221///
222/// ```
223/// # use bevy_ecs::prelude::*;
224/// #[derive(Component)]
225/// #[require(C = init_c())]
226/// struct A;
227///
228/// #[derive(Component, PartialEq, Eq, Debug)]
229/// #[require(C = C(20))]
230/// struct B;
231///
232/// #[derive(Component, PartialEq, Eq, Debug)]
233/// struct C(usize);
234///
235/// fn init_c() -> C {
236/// C(10)
237/// }
238///
239/// # let mut world = World::default();
240/// // This will implicitly also insert C with the init_c() constructor
241/// let id = world.spawn(A).id();
242/// assert_eq!(&C(10), world.entity(id).get::<C>().unwrap());
243///
244/// // This will implicitly also insert C with the `|| C(20)` constructor closure
245/// let id = world.spawn(B).id();
246/// assert_eq!(&C(20), world.entity(id).get::<C>().unwrap());
247/// ```
248///
249/// Required components are _recursive_. This means, if a Required Component has required components,
250/// those components will _also_ be inserted if they are missing:
251///
252/// ```
253/// # use bevy_ecs::prelude::*;
254/// #[derive(Component)]
255/// #[require(B)]
256/// struct A;
257///
258/// #[derive(Component, Default, PartialEq, Eq, Debug)]
259/// #[require(C)]
260/// struct B(usize);
261///
262/// #[derive(Component, Default, PartialEq, Eq, Debug)]
263/// struct C(u32);
264///
265/// # let mut world = World::default();
266/// // This will implicitly also insert B and C with their Default constructors
267/// let id = world.spawn(A).id();
268/// assert_eq!(&B(0), world.entity(id).get::<B>().unwrap());
269/// assert_eq!(&C(0), world.entity(id).get::<C>().unwrap());
270/// ```
271///
272/// Note that cycles in the "component require tree" will result in stack overflows when attempting to
273/// insert a component.
274///
275/// This "multiple inheritance" pattern does mean that it is possible to have duplicate requires for a given type
276/// at different levels of the inheritance tree:
277///
278/// ```
279/// # use bevy_ecs::prelude::*;
280/// #[derive(Component)]
281/// struct X(usize);
282///
283/// #[derive(Component, Default)]
284/// #[require(X(1))]
285/// struct Y;
286///
287/// #[derive(Component)]
288/// #[require(
289/// Y,
290/// X(2),
291/// )]
292/// struct Z;
293///
294/// # let mut world = World::default();
295/// // In this case, the x2 constructor is used for X
296/// let id = world.spawn(Z).id();
297/// assert_eq!(2, world.entity(id).get::<X>().unwrap().0);
298/// ```
299///
300/// In general, this shouldn't happen often, but when it does the algorithm for choosing the constructor from the tree is simple and predictable:
301/// 1. A constructor from a direct `#[require()]`, if one exists, is selected with priority.
302/// 2. Otherwise, perform a Depth First Search on the tree of requirements and select the first one found.
303///
304/// From a user perspective, just think about this as the following:
305/// 1. Specifying a required component constructor for Foo directly on a spawned component Bar will result in that constructor being used (and overriding existing constructors lower in the inheritance tree). This is the classic "inheritance override" behavior people expect.
306/// 2. For cases where "multiple inheritance" results in constructor clashes, Components should be listed in "importance order". List a component earlier in the requirement list to initialize its inheritance tree earlier.
307///
308/// ## Registering required components at runtime
309///
310/// In most cases, required components should be registered using the `require` attribute as shown above.
311/// However, in some cases, it may be useful to register required components at runtime.
312///
313/// This can be done through [`World::register_required_components`] or [`World::register_required_components_with`]
314/// for the [`Default`] and custom constructors respectively:
315///
316/// ```
317/// # use bevy_ecs::prelude::*;
318/// #[derive(Component)]
319/// struct A;
320///
321/// #[derive(Component, Default, PartialEq, Eq, Debug)]
322/// struct B(usize);
323///
324/// #[derive(Component, PartialEq, Eq, Debug)]
325/// struct C(u32);
326///
327/// # let mut world = World::default();
328/// // Register B as required by A and C as required by B.
329/// world.register_required_components::<A, B>();
330/// world.register_required_components_with::<B, C>(|| C(2));
331///
332/// // This will implicitly also insert B with its Default constructor
333/// // and C with the custom constructor defined by B.
334/// let id = world.spawn(A).id();
335/// assert_eq!(&B(0), world.entity(id).get::<B>().unwrap());
336/// assert_eq!(&C(2), world.entity(id).get::<C>().unwrap());
337/// ```
338///
339/// Similar rules as before apply to duplicate requires fer a given type at different levels
340/// of the inheritance tree. `A` requiring `C` directly would take precedence over indirectly
341/// requiring it through `A` requiring `B` and `B` requiring `C`.
342///
343/// Unlike with the `require` attribute, directly requiring the same component multiple times
344/// for the same component will result in a panic. This is done to prevent conflicting constructors
345/// and confusing ordering dependencies.
346///
347/// Note that requirements must currently be registered before the requiring component is inserted
348/// into the world for the first time. Registering requirements after this will lead to a panic.
349///
350/// # Relationships between Entities
351///
352/// Sometimes it is useful to define relationships between entities. A common example is the
353/// parent / child relationship. Since Components are how data is stored for Entities, one might
354/// naturally think to create a Component which has a field of type [`Entity`].
355///
356/// To facilitate this pattern, Bevy provides the [`Relationship`](`crate::relationship::Relationship`)
357/// trait. You can derive the [`Relationship`](`crate::relationship::Relationship`) and
358/// [`RelationshipTarget`](`crate::relationship::RelationshipTarget`) traits in addition to the
359/// Component trait in order to implement data driven relationships between entities, see the trait
360/// docs for more details.
361///
362/// In addition, Bevy provides canonical implementations of the parent / child relationship via the
363/// [`ChildOf`](crate::hierarchy::ChildOf) [`Relationship`](crate::relationship::Relationship) and
364/// the [`Children`](crate::hierarchy::Children)
365/// [`RelationshipTarget`](crate::relationship::RelationshipTarget).
366///
367/// # Adding component's hooks
368///
369/// See [`ComponentHooks`] for a detailed explanation of component's hooks.
370///
371/// Alternatively to the example shown in [`ComponentHooks`]' documentation, hooks can be configured using following attributes:
372/// - `#[component(on_add = on_add_function)]`
373/// - `#[component(on_insert = on_insert_function)]`
374/// - `#[component(on_replace = on_replace_function)]`
375/// - `#[component(on_remove = on_remove_function)]`
376///
377/// ```
378/// # use bevy_ecs::component::{Component, HookContext};
379/// # use bevy_ecs::world::DeferredWorld;
380/// # use bevy_ecs::entity::Entity;
381/// # use bevy_ecs::component::ComponentId;
382/// # use core::panic::Location;
383/// #
384/// #[derive(Component)]
385/// #[component(on_add = my_on_add_hook)]
386/// #[component(on_insert = my_on_insert_hook)]
387/// // Another possible way of configuring hooks:
388/// // #[component(on_add = my_on_add_hook, on_insert = my_on_insert_hook)]
389/// //
390/// // We don't have a replace or remove hook, so we can leave them out:
391/// // #[component(on_replace = my_on_replace_hook, on_remove = my_on_remove_hook)]
392/// struct ComponentA;
393///
394/// fn my_on_add_hook(world: DeferredWorld, context: HookContext) {
395/// // ...
396/// }
397///
398/// // You can also destructure items directly in the signature
399/// fn my_on_insert_hook(world: DeferredWorld, HookContext { caller, .. }: HookContext) {
400/// // ...
401/// }
402/// ```
403///
404/// This also supports function calls that yield closures
405///
406/// ```
407/// # use bevy_ecs::component::{Component, HookContext};
408/// # use bevy_ecs::world::DeferredWorld;
409/// #
410/// #[derive(Component)]
411/// #[component(on_add = my_msg_hook("hello"))]
412/// #[component(on_despawn = my_msg_hook("yoink"))]
413/// struct ComponentA;
414///
415/// // a hook closure generating function
416/// fn my_msg_hook(message: &'static str) -> impl Fn(DeferredWorld, HookContext) {
417/// move |_world, _ctx| {
418/// println!("{message}");
419/// }
420/// }
421/// ```
422///
423/// # Implementing the trait for foreign types
424///
425/// As a consequence of the [orphan rule], it is not possible to separate into two different crates the implementation of `Component` from the definition of a type.
426/// This means that it is not possible to directly have a type defined in a third party library as a component.
427/// This important limitation can be easily worked around using the [newtype pattern]:
428/// this makes it possible to locally define and implement `Component` for a tuple struct that wraps the foreign type.
429/// The following example gives a demonstration of this pattern.
430///
431/// ```
432/// // `Component` is defined in the `bevy_ecs` crate.
433/// use bevy_ecs::component::Component;
434///
435/// // `Duration` is defined in the `std` crate.
436/// use std::time::Duration;
437///
438/// // It is not possible to implement `Component` for `Duration` from this position, as they are
439/// // both foreign items, defined in an external crate. However, nothing prevents to define a new
440/// // `Cooldown` type that wraps `Duration`. As `Cooldown` is defined in a local crate, it is
441/// // possible to implement `Component` for it.
442/// #[derive(Component)]
443/// struct Cooldown(Duration);
444/// ```
445///
446/// [orphan rule]: https://doc.rust-lang.org/book/ch10-02-traits.html#implementing-a-trait-on-a-type
447/// [newtype pattern]: https://doc.rust-lang.org/book/ch19-03-advanced-traits.html#using-the-newtype-pattern-to-implement-external-traits-on-external-types
448///
449/// # `!Sync` Components
450/// A `!Sync` type cannot implement `Component`. However, it is possible to wrap a `Send` but not `Sync`
451/// type in [`SyncCell`] or the currently unstable [`Exclusive`] to make it `Sync`. This forces only
452/// having mutable access (`&mut T` only, never `&T`), but makes it safe to reference across multiple
453/// threads.
454///
455/// This will fail to compile since `RefCell` is `!Sync`.
456/// ```compile_fail
457/// # use std::cell::RefCell;
458/// # use bevy_ecs::component::Component;
459/// #[derive(Component)]
460/// struct NotSync {
461/// counter: RefCell<usize>,
462/// }
463/// ```
464///
465/// This will compile since the `RefCell` is wrapped with `SyncCell`.
466/// ```
467/// # use std::cell::RefCell;
468/// # use bevy_ecs::component::Component;
469/// use bevy_utils::synccell::SyncCell;
470///
471/// // This will compile.
472/// #[derive(Component)]
473/// struct ActuallySync {
474/// counter: SyncCell<RefCell<usize>>,
475/// }
476/// ```
477///
478/// [`SyncCell`]: bevy_utils::synccell::SyncCell
479/// [`Exclusive`]: https://doc.rust-lang.org/nightly/std/sync/struct.Exclusive.html
480#[diagnostic::on_unimplemented(
481 message = "`{Self}` is not a `Component`",
482 label = "invalid `Component`",
483 note = "consider annotating `{Self}` with `#[derive(Component)]`"
484)]
485pub trait Component: Send + Sync + 'static {
486 /// A constant indicating the storage type used for this component.
487 const STORAGE_TYPE: StorageType;
488
489 /// A marker type to assist Bevy with determining if this component is
490 /// mutable, or immutable. Mutable components will have [`Component<Mutability = Mutable>`],
491 /// while immutable components will instead have [`Component<Mutability = Immutable>`].
492 ///
493 /// * For a component to be mutable, this type must be [`Mutable`].
494 /// * For a component to be immutable, this type must be [`Immutable`].
495 type Mutability: ComponentMutability;
496
497 /// Called when registering this component, allowing mutable access to its [`ComponentHooks`].
498 #[deprecated(
499 since = "0.16.0",
500 note = "Use the individual hook methods instead (e.g., `Component::on_add`, etc.)"
501 )]
502 fn register_component_hooks(hooks: &mut ComponentHooks) {
503 hooks.update_from_component::<Self>();
504 }
505
506 /// Gets the `on_add` [`ComponentHook`] for this [`Component`] if one is defined.
507 fn on_add() -> Option<ComponentHook> {
508 None
509 }
510
511 /// Gets the `on_insert` [`ComponentHook`] for this [`Component`] if one is defined.
512 fn on_insert() -> Option<ComponentHook> {
513 None
514 }
515
516 /// Gets the `on_replace` [`ComponentHook`] for this [`Component`] if one is defined.
517 fn on_replace() -> Option<ComponentHook> {
518 None
519 }
520
521 /// Gets the `on_remove` [`ComponentHook`] for this [`Component`] if one is defined.
522 fn on_remove() -> Option<ComponentHook> {
523 None
524 }
525
526 /// Gets the `on_despawn` [`ComponentHook`] for this [`Component`] if one is defined.
527 fn on_despawn() -> Option<ComponentHook> {
528 None
529 }
530
531 /// Registers required components.
532 fn register_required_components(
533 _component_id: ComponentId,
534 _components: &mut ComponentsRegistrator,
535 _required_components: &mut RequiredComponents,
536 _inheritance_depth: u16,
537 _recursion_check_stack: &mut Vec<ComponentId>,
538 ) {
539 }
540
541 /// Called when registering this component, allowing to override clone function (or disable cloning altogether) for this component.
542 ///
543 /// See [Handlers section of `EntityClonerBuilder`](crate::entity::EntityClonerBuilder#handlers) to understand how this affects handler priority.
544 #[inline]
545 fn clone_behavior() -> ComponentCloneBehavior {
546 ComponentCloneBehavior::Default
547 }
548
549 /// Maps the entities on this component using the given [`EntityMapper`]. This is used to remap entities in contexts like scenes and entity cloning.
550 /// When deriving [`Component`], this is populated by annotating fields containing entities with `#[entities]`
551 ///
552 /// ```
553 /// # use bevy_ecs::{component::Component, entity::Entity};
554 /// #[derive(Component)]
555 /// struct Inventory {
556 /// #[entities]
557 /// items: Vec<Entity>
558 /// }
559 /// ```
560 ///
561 /// Fields with `#[entities]` must implement [`MapEntities`](crate::entity::MapEntities).
562 #[inline]
563 fn map_entities<E: EntityMapper>(_this: &mut Self, _mapper: &mut E) {}
564}
565
566mod private {
567 pub trait Seal {}
568}
569
570/// The mutability option for a [`Component`]. This can either be:
571/// * [`Mutable`]
572/// * [`Immutable`]
573///
574/// This is controlled through either [`Component::Mutability`] or `#[component(immutable)]`
575/// when using the derive macro.
576///
577/// Immutable components are guaranteed to never have an exclusive reference,
578/// `&mut ...`, created while inserted onto an entity.
579/// In all other ways, they are identical to mutable components.
580/// This restriction allows hooks to observe all changes made to an immutable
581/// component, effectively turning the `OnInsert` and `OnReplace` hooks into a
582/// `OnMutate` hook.
583/// This is not practical for mutable components, as the runtime cost of invoking
584/// a hook for every exclusive reference created would be far too high.
585///
586/// # Examples
587///
588/// ```rust
589/// # use bevy_ecs::component::Component;
590/// #
591/// #[derive(Component)]
592/// #[component(immutable)]
593/// struct ImmutableFoo;
594/// ```
595pub trait ComponentMutability: private::Seal + 'static {
596 /// Boolean to indicate if this mutability setting implies a mutable or immutable
597 /// component.
598 const MUTABLE: bool;
599}
600
601/// Parameter indicating a [`Component`] is immutable.
602///
603/// See [`ComponentMutability`] for details.
604pub struct Immutable;
605
606impl private::Seal for Immutable {}
607impl ComponentMutability for Immutable {
608 const MUTABLE: bool = false;
609}
610
611/// Parameter indicating a [`Component`] is mutable.
612///
613/// See [`ComponentMutability`] for details.
614pub struct Mutable;
615
616impl private::Seal for Mutable {}
617impl ComponentMutability for Mutable {
618 const MUTABLE: bool = true;
619}
620
621/// The storage used for a specific component type.
622///
623/// # Examples
624/// The [`StorageType`] for a component is configured via the derive attribute
625///
626/// ```
627/// # use bevy_ecs::{prelude::*, component::*};
628/// #[derive(Component)]
629/// #[component(storage = "SparseSet")]
630/// struct A;
631/// ```
632#[derive(Debug, Copy, Clone, Default, Eq, PartialEq)]
633pub enum StorageType {
634 /// Provides fast and cache-friendly iteration, but slower addition and removal of components.
635 /// This is the default storage type.
636 #[default]
637 Table,
638 /// Provides fast addition and removal of components, but slower iteration.
639 SparseSet,
640}
641
642/// The type used for [`Component`] lifecycle hooks such as `on_add`, `on_insert` or `on_remove`.
643pub type ComponentHook = for<'w> fn(DeferredWorld<'w>, HookContext);
644
645/// Context provided to a [`ComponentHook`].
646#[derive(Clone, Copy, Debug)]
647pub struct HookContext {
648 /// The [`Entity`] this hook was invoked for.
649 pub entity: Entity,
650 /// The [`ComponentId`] this hook was invoked for.
651 pub component_id: ComponentId,
652 /// The caller location is `Some` if the `track_caller` feature is enabled.
653 pub caller: MaybeLocation,
654 /// Configures how relationship hooks will run
655 pub relationship_hook_mode: RelationshipHookMode,
656}
657
658/// [`World`]-mutating functions that run as part of lifecycle events of a [`Component`].
659///
660/// Hooks are functions that run when a component is added, overwritten, or removed from an entity.
661/// These are intended to be used for structural side effects that need to happen when a component is added or removed,
662/// and are not intended for general-purpose logic.
663///
664/// For example, you might use a hook to update a cached index when a component is added,
665/// to clean up resources when a component is removed,
666/// or to keep hierarchical data structures across entities in sync.
667///
668/// This information is stored in the [`ComponentInfo`] of the associated component.
669///
670/// There is two ways of configuring hooks for a component:
671/// 1. Defining the [`Component::register_component_hooks`] method (see [`Component`])
672/// 2. Using the [`World::register_component_hooks`] method
673///
674/// # Example 2
675///
676/// ```
677/// use bevy_ecs::prelude::*;
678/// use bevy_platform_support::collections::HashSet;
679///
680/// #[derive(Component)]
681/// struct MyTrackedComponent;
682///
683/// #[derive(Resource, Default)]
684/// struct TrackedEntities(HashSet<Entity>);
685///
686/// let mut world = World::new();
687/// world.init_resource::<TrackedEntities>();
688///
689/// // No entities with `MyTrackedComponent` have been added yet, so we can safely add component hooks
690/// let mut tracked_component_query = world.query::<&MyTrackedComponent>();
691/// assert!(tracked_component_query.iter(&world).next().is_none());
692///
693/// world.register_component_hooks::<MyTrackedComponent>().on_add(|mut world, context| {
694/// let mut tracked_entities = world.resource_mut::<TrackedEntities>();
695/// tracked_entities.0.insert(context.entity);
696/// });
697///
698/// world.register_component_hooks::<MyTrackedComponent>().on_remove(|mut world, context| {
699/// let mut tracked_entities = world.resource_mut::<TrackedEntities>();
700/// tracked_entities.0.remove(&context.entity);
701/// });
702///
703/// let entity = world.spawn(MyTrackedComponent).id();
704/// let tracked_entities = world.resource::<TrackedEntities>();
705/// assert!(tracked_entities.0.contains(&entity));
706///
707/// world.despawn(entity);
708/// let tracked_entities = world.resource::<TrackedEntities>();
709/// assert!(!tracked_entities.0.contains(&entity));
710/// ```
711#[derive(Debug, Clone, Default)]
712pub struct ComponentHooks {
713 pub(crate) on_add: Option<ComponentHook>,
714 pub(crate) on_insert: Option<ComponentHook>,
715 pub(crate) on_replace: Option<ComponentHook>,
716 pub(crate) on_remove: Option<ComponentHook>,
717 pub(crate) on_despawn: Option<ComponentHook>,
718}
719
720impl ComponentHooks {
721 pub(crate) fn update_from_component<C: Component + ?Sized>(&mut self) -> &mut Self {
722 if let Some(hook) = C::on_add() {
723 self.on_add(hook);
724 }
725 if let Some(hook) = C::on_insert() {
726 self.on_insert(hook);
727 }
728 if let Some(hook) = C::on_replace() {
729 self.on_replace(hook);
730 }
731 if let Some(hook) = C::on_remove() {
732 self.on_remove(hook);
733 }
734 if let Some(hook) = C::on_despawn() {
735 self.on_despawn(hook);
736 }
737
738 self
739 }
740
741 /// Register a [`ComponentHook`] that will be run when this component is added to an entity.
742 /// An `on_add` hook will always run before `on_insert` hooks. Spawning an entity counts as
743 /// adding all of its components.
744 ///
745 /// # Panics
746 ///
747 /// Will panic if the component already has an `on_add` hook
748 pub fn on_add(&mut self, hook: ComponentHook) -> &mut Self {
749 self.try_on_add(hook)
750 .expect("Component already has an on_add hook")
751 }
752
753 /// Register a [`ComponentHook`] that will be run when this component is added (with `.insert`)
754 /// or replaced.
755 ///
756 /// An `on_insert` hook always runs after any `on_add` hooks (if the entity didn't already have the component).
757 ///
758 /// # Warning
759 ///
760 /// The hook won't run if the component is already present and is only mutated, such as in a system via a query.
761 /// As a result, this is *not* an appropriate mechanism for reliably updating indexes and other caches.
762 ///
763 /// # Panics
764 ///
765 /// Will panic if the component already has an `on_insert` hook
766 pub fn on_insert(&mut self, hook: ComponentHook) -> &mut Self {
767 self.try_on_insert(hook)
768 .expect("Component already has an on_insert hook")
769 }
770
771 /// Register a [`ComponentHook`] that will be run when this component is about to be dropped,
772 /// such as being replaced (with `.insert`) or removed.
773 ///
774 /// If this component is inserted onto an entity that already has it, this hook will run before the value is replaced,
775 /// allowing access to the previous data just before it is dropped.
776 /// This hook does *not* run if the entity did not already have this component.
777 ///
778 /// An `on_replace` hook always runs before any `on_remove` hooks (if the component is being removed from the entity).
779 ///
780 /// # Warning
781 ///
782 /// The hook won't run if the component is already present and is only mutated, such as in a system via a query.
783 /// As a result, this is *not* an appropriate mechanism for reliably updating indexes and other caches.
784 ///
785 /// # Panics
786 ///
787 /// Will panic if the component already has an `on_replace` hook
788 pub fn on_replace(&mut self, hook: ComponentHook) -> &mut Self {
789 self.try_on_replace(hook)
790 .expect("Component already has an on_replace hook")
791 }
792
793 /// Register a [`ComponentHook`] that will be run when this component is removed from an entity.
794 /// Despawning an entity counts as removing all of its components.
795 ///
796 /// # Panics
797 ///
798 /// Will panic if the component already has an `on_remove` hook
799 pub fn on_remove(&mut self, hook: ComponentHook) -> &mut Self {
800 self.try_on_remove(hook)
801 .expect("Component already has an on_remove hook")
802 }
803
804 /// Register a [`ComponentHook`] that will be run for each component on an entity when it is despawned.
805 ///
806 /// # Panics
807 ///
808 /// Will panic if the component already has an `on_despawn` hook
809 pub fn on_despawn(&mut self, hook: ComponentHook) -> &mut Self {
810 self.try_on_despawn(hook)
811 .expect("Component already has an on_despawn hook")
812 }
813
814 /// Attempt to register a [`ComponentHook`] that will be run when this component is added to an entity.
815 ///
816 /// This is a fallible version of [`Self::on_add`].
817 ///
818 /// Returns `None` if the component already has an `on_add` hook.
819 pub fn try_on_add(&mut self, hook: ComponentHook) -> Option<&mut Self> {
820 if self.on_add.is_some() {
821 return None;
822 }
823 self.on_add = Some(hook);
824 Some(self)
825 }
826
827 /// Attempt to register a [`ComponentHook`] that will be run when this component is added (with `.insert`)
828 ///
829 /// This is a fallible version of [`Self::on_insert`].
830 ///
831 /// Returns `None` if the component already has an `on_insert` hook.
832 pub fn try_on_insert(&mut self, hook: ComponentHook) -> Option<&mut Self> {
833 if self.on_insert.is_some() {
834 return None;
835 }
836 self.on_insert = Some(hook);
837 Some(self)
838 }
839
840 /// Attempt to register a [`ComponentHook`] that will be run when this component is replaced (with `.insert`) or removed
841 ///
842 /// This is a fallible version of [`Self::on_replace`].
843 ///
844 /// Returns `None` if the component already has an `on_replace` hook.
845 pub fn try_on_replace(&mut self, hook: ComponentHook) -> Option<&mut Self> {
846 if self.on_replace.is_some() {
847 return None;
848 }
849 self.on_replace = Some(hook);
850 Some(self)
851 }
852
853 /// Attempt to register a [`ComponentHook`] that will be run when this component is removed from an entity.
854 ///
855 /// This is a fallible version of [`Self::on_remove`].
856 ///
857 /// Returns `None` if the component already has an `on_remove` hook.
858 pub fn try_on_remove(&mut self, hook: ComponentHook) -> Option<&mut Self> {
859 if self.on_remove.is_some() {
860 return None;
861 }
862 self.on_remove = Some(hook);
863 Some(self)
864 }
865
866 /// Attempt to register a [`ComponentHook`] that will be run for each component on an entity when it is despawned.
867 ///
868 /// This is a fallible version of [`Self::on_despawn`].
869 ///
870 /// Returns `None` if the component already has an `on_despawn` hook.
871 pub fn try_on_despawn(&mut self, hook: ComponentHook) -> Option<&mut Self> {
872 if self.on_despawn.is_some() {
873 return None;
874 }
875 self.on_despawn = Some(hook);
876 Some(self)
877 }
878}
879
880/// Stores metadata for a type of component or resource stored in a specific [`World`].
881#[derive(Debug, Clone)]
882pub struct ComponentInfo {
883 id: ComponentId,
884 descriptor: ComponentDescriptor,
885 hooks: ComponentHooks,
886 required_components: RequiredComponents,
887 required_by: HashSet<ComponentId>,
888}
889
890impl ComponentInfo {
891 /// Returns a value uniquely identifying the current component.
892 #[inline]
893 pub fn id(&self) -> ComponentId {
894 self.id
895 }
896
897 /// Returns the name of the current component.
898 #[inline]
899 pub fn name(&self) -> &str {
900 &self.descriptor.name
901 }
902
903 /// Returns `true` if the current component is mutable.
904 #[inline]
905 pub fn mutable(&self) -> bool {
906 self.descriptor.mutable
907 }
908
909 /// Returns [`ComponentCloneBehavior`] of the current component.
910 #[inline]
911 pub fn clone_behavior(&self) -> &ComponentCloneBehavior {
912 &self.descriptor.clone_behavior
913 }
914
915 /// Returns the [`TypeId`] of the underlying component type.
916 /// Returns `None` if the component does not correspond to a Rust type.
917 #[inline]
918 pub fn type_id(&self) -> Option<TypeId> {
919 self.descriptor.type_id
920 }
921
922 /// Returns the layout used to store values of this component in memory.
923 #[inline]
924 pub fn layout(&self) -> Layout {
925 self.descriptor.layout
926 }
927
928 #[inline]
929 /// Get the function which should be called to clean up values of
930 /// the underlying component type. This maps to the
931 /// [`Drop`] implementation for 'normal' Rust components
932 ///
933 /// Returns `None` if values of the underlying component type don't
934 /// need to be dropped, e.g. as reported by [`needs_drop`].
935 pub fn drop(&self) -> Option<unsafe fn(OwningPtr<'_>)> {
936 self.descriptor.drop
937 }
938
939 /// Returns a value indicating the storage strategy for the current component.
940 #[inline]
941 pub fn storage_type(&self) -> StorageType {
942 self.descriptor.storage_type
943 }
944
945 /// Returns `true` if the underlying component type can be freely shared between threads.
946 /// If this returns `false`, then extra care must be taken to ensure that components
947 /// are not accessed from the wrong thread.
948 #[inline]
949 pub fn is_send_and_sync(&self) -> bool {
950 self.descriptor.is_send_and_sync
951 }
952
953 /// Create a new [`ComponentInfo`].
954 pub(crate) fn new(id: ComponentId, descriptor: ComponentDescriptor) -> Self {
955 ComponentInfo {
956 id,
957 descriptor,
958 hooks: Default::default(),
959 required_components: Default::default(),
960 required_by: Default::default(),
961 }
962 }
963
964 /// Update the given flags to include any [`ComponentHook`] registered to self
965 #[inline]
966 pub(crate) fn update_archetype_flags(&self, flags: &mut ArchetypeFlags) {
967 if self.hooks().on_add.is_some() {
968 flags.insert(ArchetypeFlags::ON_ADD_HOOK);
969 }
970 if self.hooks().on_insert.is_some() {
971 flags.insert(ArchetypeFlags::ON_INSERT_HOOK);
972 }
973 if self.hooks().on_replace.is_some() {
974 flags.insert(ArchetypeFlags::ON_REPLACE_HOOK);
975 }
976 if self.hooks().on_remove.is_some() {
977 flags.insert(ArchetypeFlags::ON_REMOVE_HOOK);
978 }
979 if self.hooks().on_despawn.is_some() {
980 flags.insert(ArchetypeFlags::ON_DESPAWN_HOOK);
981 }
982 }
983
984 /// Provides a reference to the collection of hooks associated with this [`Component`]
985 pub fn hooks(&self) -> &ComponentHooks {
986 &self.hooks
987 }
988
989 /// Retrieves the [`RequiredComponents`] collection, which contains all required components (and their constructors)
990 /// needed by this component. This includes _recursive_ required components.
991 pub fn required_components(&self) -> &RequiredComponents {
992 &self.required_components
993 }
994}
995
996/// A value which uniquely identifies the type of a [`Component`] or [`Resource`] within a
997/// [`World`].
998///
999/// Each time a new `Component` type is registered within a `World` using
1000/// e.g. [`World::register_component`] or [`World::register_component_with_descriptor`]
1001/// or a Resource with e.g. [`World::init_resource`],
1002/// a corresponding `ComponentId` is created to track it.
1003///
1004/// While the distinction between `ComponentId` and [`TypeId`] may seem superficial, breaking them
1005/// into two separate but related concepts allows components to exist outside of Rust's type system.
1006/// Each Rust type registered as a `Component` will have a corresponding `ComponentId`, but additional
1007/// `ComponentId`s may exist in a `World` to track components which cannot be
1008/// represented as Rust types for scripting or other advanced use-cases.
1009///
1010/// A `ComponentId` is tightly coupled to its parent `World`. Attempting to use a `ComponentId` from
1011/// one `World` to access the metadata of a `Component` in a different `World` is undefined behavior
1012/// and must not be attempted.
1013///
1014/// Given a type `T` which implements [`Component`], the `ComponentId` for `T` can be retrieved
1015/// from a `World` using [`World::component_id()`] or via [`Components::component_id()`]. Access
1016/// to the `ComponentId` for a [`Resource`] is available via [`Components::resource_id()`].
1017#[derive(Debug, Copy, Clone, Hash, Ord, PartialOrd, Eq, PartialEq)]
1018#[cfg_attr(
1019 feature = "bevy_reflect",
1020 derive(Reflect),
1021 reflect(Debug, Hash, PartialEq, Clone)
1022)]
1023pub struct ComponentId(usize);
1024
1025impl ComponentId {
1026 /// Creates a new [`ComponentId`].
1027 ///
1028 /// The `index` is a unique value associated with each type of component in a given world.
1029 /// Usually, this value is taken from a counter incremented for each type of component registered with the world.
1030 #[inline]
1031 pub const fn new(index: usize) -> ComponentId {
1032 ComponentId(index)
1033 }
1034
1035 /// Returns the index of the current component.
1036 #[inline]
1037 pub fn index(self) -> usize {
1038 self.0
1039 }
1040}
1041
1042impl SparseSetIndex for ComponentId {
1043 #[inline]
1044 fn sparse_set_index(&self) -> usize {
1045 self.index()
1046 }
1047
1048 #[inline]
1049 fn get_sparse_set_index(value: usize) -> Self {
1050 Self(value)
1051 }
1052}
1053
1054/// A value describing a component or resource, which may or may not correspond to a Rust type.
1055#[derive(Clone)]
1056pub struct ComponentDescriptor {
1057 name: Cow<'static, str>,
1058 // SAFETY: This must remain private. It must match the statically known StorageType of the
1059 // associated rust component type if one exists.
1060 storage_type: StorageType,
1061 // SAFETY: This must remain private. It must only be set to "true" if this component is
1062 // actually Send + Sync
1063 is_send_and_sync: bool,
1064 type_id: Option<TypeId>,
1065 layout: Layout,
1066 // SAFETY: this function must be safe to call with pointers pointing to items of the type
1067 // this descriptor describes.
1068 // None if the underlying type doesn't need to be dropped
1069 drop: Option<for<'a> unsafe fn(OwningPtr<'a>)>,
1070 mutable: bool,
1071 clone_behavior: ComponentCloneBehavior,
1072}
1073
1074// We need to ignore the `drop` field in our `Debug` impl
1075impl Debug for ComponentDescriptor {
1076 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1077 f.debug_struct("ComponentDescriptor")
1078 .field("name", &self.name)
1079 .field("storage_type", &self.storage_type)
1080 .field("is_send_and_sync", &self.is_send_and_sync)
1081 .field("type_id", &self.type_id)
1082 .field("layout", &self.layout)
1083 .field("mutable", &self.mutable)
1084 .field("clone_behavior", &self.clone_behavior)
1085 .finish()
1086 }
1087}
1088
1089impl ComponentDescriptor {
1090 /// # Safety
1091 ///
1092 /// `x` must point to a valid value of type `T`.
1093 unsafe fn drop_ptr<T>(x: OwningPtr<'_>) {
1094 // SAFETY: Contract is required to be upheld by the caller.
1095 unsafe {
1096 x.drop_as::<T>();
1097 }
1098 }
1099
1100 /// Create a new `ComponentDescriptor` for the type `T`.
1101 pub fn new<T: Component>() -> Self {
1102 Self {
1103 name: Cow::Borrowed(core::any::type_name::<T>()),
1104 storage_type: T::STORAGE_TYPE,
1105 is_send_and_sync: true,
1106 type_id: Some(TypeId::of::<T>()),
1107 layout: Layout::new::<T>(),
1108 drop: needs_drop::<T>().then_some(Self::drop_ptr::<T> as _),
1109 mutable: T::Mutability::MUTABLE,
1110 clone_behavior: T::clone_behavior(),
1111 }
1112 }
1113
1114 /// Create a new `ComponentDescriptor`.
1115 ///
1116 /// # Safety
1117 /// - the `drop` fn must be usable on a pointer with a value of the layout `layout`
1118 /// - the component type must be safe to access from any thread (Send + Sync in rust terms)
1119 pub unsafe fn new_with_layout(
1120 name: impl Into<Cow<'static, str>>,
1121 storage_type: StorageType,
1122 layout: Layout,
1123 drop: Option<for<'a> unsafe fn(OwningPtr<'a>)>,
1124 mutable: bool,
1125 clone_behavior: ComponentCloneBehavior,
1126 ) -> Self {
1127 Self {
1128 name: name.into(),
1129 storage_type,
1130 is_send_and_sync: true,
1131 type_id: None,
1132 layout,
1133 drop,
1134 mutable,
1135 clone_behavior,
1136 }
1137 }
1138
1139 /// Create a new `ComponentDescriptor` for a resource.
1140 ///
1141 /// The [`StorageType`] for resources is always [`StorageType::Table`].
1142 pub fn new_resource<T: Resource>() -> Self {
1143 Self {
1144 name: Cow::Borrowed(core::any::type_name::<T>()),
1145 // PERF: `SparseStorage` may actually be a more
1146 // reasonable choice as `storage_type` for resources.
1147 storage_type: StorageType::Table,
1148 is_send_and_sync: true,
1149 type_id: Some(TypeId::of::<T>()),
1150 layout: Layout::new::<T>(),
1151 drop: needs_drop::<T>().then_some(Self::drop_ptr::<T> as _),
1152 mutable: true,
1153 clone_behavior: ComponentCloneBehavior::Default,
1154 }
1155 }
1156
1157 fn new_non_send<T: Any>(storage_type: StorageType) -> Self {
1158 Self {
1159 name: Cow::Borrowed(core::any::type_name::<T>()),
1160 storage_type,
1161 is_send_and_sync: false,
1162 type_id: Some(TypeId::of::<T>()),
1163 layout: Layout::new::<T>(),
1164 drop: needs_drop::<T>().then_some(Self::drop_ptr::<T> as _),
1165 mutable: true,
1166 clone_behavior: ComponentCloneBehavior::Default,
1167 }
1168 }
1169
1170 /// Returns a value indicating the storage strategy for the current component.
1171 #[inline]
1172 pub fn storage_type(&self) -> StorageType {
1173 self.storage_type
1174 }
1175
1176 /// Returns the [`TypeId`] of the underlying component type.
1177 /// Returns `None` if the component does not correspond to a Rust type.
1178 #[inline]
1179 pub fn type_id(&self) -> Option<TypeId> {
1180 self.type_id
1181 }
1182
1183 /// Returns the name of the current component.
1184 #[inline]
1185 pub fn name(&self) -> &str {
1186 self.name.as_ref()
1187 }
1188
1189 /// Returns whether this component is mutable.
1190 #[inline]
1191 pub fn mutable(&self) -> bool {
1192 self.mutable
1193 }
1194}
1195
1196/// Function type that can be used to clone an entity.
1197pub type ComponentCloneFn = fn(&SourceComponent, &mut ComponentCloneCtx);
1198
1199/// The clone behavior to use when cloning a [`Component`].
1200#[derive(Clone, Debug, Default, PartialEq, Eq)]
1201pub enum ComponentCloneBehavior {
1202 /// Uses the default behavior (which is passed to [`ComponentCloneBehavior::resolve`])
1203 #[default]
1204 Default,
1205 /// Do not clone this component.
1206 Ignore,
1207 /// Uses a custom [`ComponentCloneFn`].
1208 Custom(ComponentCloneFn),
1209}
1210
1211impl ComponentCloneBehavior {
1212 /// Set clone handler based on `Clone` trait.
1213 ///
1214 /// If set as a handler for a component that is not the same as the one used to create this handler, it will panic.
1215 pub fn clone<C: Component + Clone>() -> Self {
1216 Self::Custom(component_clone_via_clone::<C>)
1217 }
1218
1219 /// Set clone handler based on `Reflect` trait.
1220 #[cfg(feature = "bevy_reflect")]
1221 pub fn reflect() -> Self {
1222 Self::Custom(component_clone_via_reflect)
1223 }
1224
1225 /// Returns the "global default"
1226 pub fn global_default_fn() -> ComponentCloneFn {
1227 #[cfg(feature = "bevy_reflect")]
1228 return component_clone_via_reflect;
1229 #[cfg(not(feature = "bevy_reflect"))]
1230 return component_clone_ignore;
1231 }
1232
1233 /// Resolves the [`ComponentCloneBehavior`] to a [`ComponentCloneFn`]. If [`ComponentCloneBehavior::Default`] is
1234 /// specified, the given `default` function will be used.
1235 pub fn resolve(&self, default: ComponentCloneFn) -> ComponentCloneFn {
1236 match self {
1237 ComponentCloneBehavior::Default => default,
1238 ComponentCloneBehavior::Ignore => component_clone_ignore,
1239 ComponentCloneBehavior::Custom(custom) => *custom,
1240 }
1241 }
1242}
1243
1244/// A queued component registration.
1245struct QueuedRegistration {
1246 registrator: Box<dyn FnOnce(&mut ComponentsRegistrator, ComponentId)>,
1247 id: ComponentId,
1248}
1249
1250impl QueuedRegistration {
1251 /// Creates the [`QueuedRegistration`].
1252 ///
1253 /// # Safety
1254 ///
1255 /// [`ComponentId`] must be unique.
1256 unsafe fn new(
1257 id: ComponentId,
1258 func: impl FnOnce(&mut ComponentsRegistrator, ComponentId) + 'static,
1259 ) -> Self {
1260 Self {
1261 registrator: Box::new(func),
1262 id,
1263 }
1264 }
1265
1266 /// Performs the registration, returning the now valid [`ComponentId`].
1267 fn register(self, registrator: &mut ComponentsRegistrator) -> ComponentId {
1268 (self.registrator)(registrator, self.id);
1269 self.id
1270 }
1271}
1272
1273/// Allows queuing components to be registered.
1274#[derive(Default)]
1275pub struct QueuedComponents {
1276 components: TypeIdMap<QueuedRegistration>,
1277 resources: TypeIdMap<QueuedRegistration>,
1278 dynamic_registrations: Vec<QueuedRegistration>,
1279}
1280
1281impl Debug for QueuedComponents {
1282 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1283 let components = self
1284 .components
1285 .iter()
1286 .map(|(type_id, queued)| (type_id, queued.id))
1287 .collect::<Vec<_>>();
1288 let resources = self
1289 .resources
1290 .iter()
1291 .map(|(type_id, queued)| (type_id, queued.id))
1292 .collect::<Vec<_>>();
1293 let dynamic_registrations = self
1294 .dynamic_registrations
1295 .iter()
1296 .map(|queued| queued.id)
1297 .collect::<Vec<_>>();
1298 write!(f, "components: {components:?}, resources: {resources:?}, dynamic_registrations: {dynamic_registrations:?}")
1299 }
1300}
1301
1302/// Generates [`ComponentId`]s.
1303#[derive(Debug, Default)]
1304pub struct ComponentIds {
1305 next: bevy_platform_support::sync::atomic::AtomicUsize,
1306}
1307
1308impl ComponentIds {
1309 /// Peeks the next [`ComponentId`] to be generated without generating it.
1310 pub fn peek(&self) -> ComponentId {
1311 ComponentId(
1312 self.next
1313 .load(bevy_platform_support::sync::atomic::Ordering::Relaxed),
1314 )
1315 }
1316
1317 /// Generates and returns the next [`ComponentId`].
1318 pub fn next(&self) -> ComponentId {
1319 ComponentId(
1320 self.next
1321 .fetch_add(1, bevy_platform_support::sync::atomic::Ordering::Relaxed),
1322 )
1323 }
1324
1325 /// Peeks the next [`ComponentId`] to be generated without generating it.
1326 pub fn peek_mut(&mut self) -> ComponentId {
1327 ComponentId(*self.next.get_mut())
1328 }
1329
1330 /// Generates and returns the next [`ComponentId`].
1331 pub fn next_mut(&mut self) -> ComponentId {
1332 let id = self.next.get_mut();
1333 let result = ComponentId(*id);
1334 *id += 1;
1335 result
1336 }
1337
1338 /// Returns the number of [`ComponentId`]s generated.
1339 pub fn len(&self) -> usize {
1340 self.peek().0
1341 }
1342
1343 /// Returns true if and only if no ids have been generated.
1344 pub fn is_empty(&self) -> bool {
1345 self.len() == 0
1346 }
1347}
1348
1349/// A type that enables queuing registration in [`Components`].
1350///
1351/// # Note
1352///
1353/// These queued registrations return [`ComponentId`]s.
1354/// These ids are not yet valid, but they will become valid
1355/// when either [`ComponentsRegistrator::apply_queued_registrations`] is called or the same registration is made directly.
1356/// In either case, the returned [`ComponentId`]s will be correct, but they are not correct yet.
1357///
1358/// Generally, that means these [`ComponentId`]s can be safely used for read-only purposes.
1359/// Modifying the contents of the world through these [`ComponentId`]s directly without waiting for them to be fully registered
1360/// and without then confirming that they have been fully registered is not supported.
1361/// Hence, extra care is needed with these [`ComponentId`]s to ensure all safety rules are followed.
1362///
1363/// As a rule of thumb, if you have mutable access to [`ComponentsRegistrator`], prefer to use that instead.
1364/// Use this only if you need to know the id of a component but do not need to modify the contents of the world based on that id.
1365pub struct ComponentsQueuedRegistrator<'w> {
1366 components: &'w Components,
1367 ids: &'w ComponentIds,
1368}
1369
1370impl Deref for ComponentsQueuedRegistrator<'_> {
1371 type Target = Components;
1372
1373 fn deref(&self) -> &Self::Target {
1374 self.components
1375 }
1376}
1377
1378impl<'w> ComponentsQueuedRegistrator<'w> {
1379 /// Constructs a new [`ComponentsQueuedRegistrator`].
1380 ///
1381 /// # Safety
1382 ///
1383 /// The [`Components`] and [`ComponentIds`] must match.
1384 /// For example, they must be from the same world.
1385 pub unsafe fn new(components: &'w Components, ids: &'w ComponentIds) -> Self {
1386 Self { components, ids }
1387 }
1388
1389 /// Queues this function to run as a component registrator.
1390 ///
1391 /// # Safety
1392 ///
1393 /// The [`TypeId`] must not already be registered or queued as a component.
1394 unsafe fn force_register_arbitrary_component(
1395 &self,
1396 type_id: TypeId,
1397 func: impl FnOnce(&mut ComponentsRegistrator, ComponentId) + 'static,
1398 ) -> ComponentId {
1399 let id = self.ids.next();
1400 self.components
1401 .queued
1402 .write()
1403 .unwrap_or_else(PoisonError::into_inner)
1404 .components
1405 .insert(
1406 type_id,
1407 // SAFETY: The id was just generated.
1408 unsafe { QueuedRegistration::new(id, func) },
1409 );
1410 id
1411 }
1412
1413 /// Queues this function to run as a resource registrator.
1414 ///
1415 /// # Safety
1416 ///
1417 /// The [`TypeId`] must not already be registered or queued as a resource.
1418 unsafe fn force_register_arbitrary_resource(
1419 &self,
1420 type_id: TypeId,
1421 func: impl FnOnce(&mut ComponentsRegistrator, ComponentId) + 'static,
1422 ) -> ComponentId {
1423 let id = self.ids.next();
1424 self.components
1425 .queued
1426 .write()
1427 .unwrap_or_else(PoisonError::into_inner)
1428 .resources
1429 .insert(
1430 type_id,
1431 // SAFETY: The id was just generated.
1432 unsafe { QueuedRegistration::new(id, func) },
1433 );
1434 id
1435 }
1436
1437 /// Queues this function to run as a dynamic registrator.
1438 fn force_register_arbitrary_dynamic(
1439 &self,
1440 func: impl FnOnce(&mut ComponentsRegistrator, ComponentId) + 'static,
1441 ) -> ComponentId {
1442 let id = self.ids.next();
1443 self.components
1444 .queued
1445 .write()
1446 .unwrap_or_else(PoisonError::into_inner)
1447 .dynamic_registrations
1448 .push(
1449 // SAFETY: The id was just generated.
1450 unsafe { QueuedRegistration::new(id, func) },
1451 );
1452 id
1453 }
1454
1455 /// This is a queued version of [`ComponentsRegistrator::register_component`].
1456 /// This will reserve an id and queue the registration.
1457 /// These registrations will be carried out at the next opportunity.
1458 ///
1459 /// # Note
1460 ///
1461 /// Technically speaking, the returned [`ComponentId`] is not valid, but it will become valid later.
1462 /// See type level docs for details.
1463 #[inline]
1464 pub fn queue_register_component<T: Component>(&self) -> ComponentId {
1465 self.component_id::<T>().unwrap_or_else(|| {
1466 // SAFETY: We just checked that this type was not in the queue.
1467 unsafe {
1468 self.force_register_arbitrary_component(TypeId::of::<T>(), |registrator, id| {
1469 // SAFETY: We just checked that this is not currently registered or queued, and if it was registered since, this would have been dropped from the queue.
1470 #[expect(unused_unsafe, reason = "More precise to specify.")]
1471 unsafe {
1472 registrator.register_component_unchecked::<T>(&mut Vec::new(), id);
1473 }
1474 })
1475 }
1476 })
1477 }
1478
1479 /// This is a queued version of [`ComponentsRegistrator::register_component_with_descriptor`].
1480 /// This will reserve an id and queue the registration.
1481 /// These registrations will be carried out at the next opportunity.
1482 ///
1483 /// # Note
1484 ///
1485 /// Technically speaking, the returned [`ComponentId`] is not valid, but it will become valid later.
1486 /// See type level docs for details.
1487 #[inline]
1488 pub fn queue_register_component_with_descriptor(
1489 &self,
1490 descriptor: ComponentDescriptor,
1491 ) -> ComponentId {
1492 self.force_register_arbitrary_dynamic(|registrator, id| {
1493 // SAFETY: Id uniqueness handled by caller.
1494 unsafe {
1495 registrator.register_component_inner(id, descriptor);
1496 }
1497 })
1498 }
1499
1500 /// This is a queued version of [`ComponentsRegistrator::register_resource`].
1501 /// This will reserve an id and queue the registration.
1502 /// These registrations will be carried out at the next opportunity.
1503 ///
1504 /// # Note
1505 ///
1506 /// Technically speaking, the returned [`ComponentId`] is not valid, but it will become valid later.
1507 /// See type level docs for details.
1508 #[inline]
1509 pub fn queue_register_resource<T: Resource>(&self) -> ComponentId {
1510 let type_id = TypeId::of::<T>();
1511 self.get_resource_id(type_id).unwrap_or_else(|| {
1512 // SAFETY: We just checked that this type was not in the queue.
1513 unsafe {
1514 self.force_register_arbitrary_resource(type_id, move |registrator, id| {
1515 // SAFETY: We just checked that this is not currently registered or queued, and if it was registered since, this would have been dropped from the queue.
1516 // SAFETY: Id uniqueness handled by caller, and the type_id matches descriptor.
1517 #[expect(unused_unsafe, reason = "More precise to specify.")]
1518 unsafe {
1519 registrator.register_resource_unchecked_with(type_id, id, || {
1520 ComponentDescriptor::new_resource::<T>()
1521 });
1522 }
1523 })
1524 }
1525 })
1526 }
1527
1528 /// This is a queued version of [`ComponentsRegistrator::register_non_send`].
1529 /// This will reserve an id and queue the registration.
1530 /// These registrations will be carried out at the next opportunity.
1531 ///
1532 /// # Note
1533 ///
1534 /// Technically speaking, the returned [`ComponentId`] is not valid, but it will become valid later.
1535 /// See type level docs for details.
1536 #[inline]
1537 pub fn queue_register_non_send<T: Any>(&self) -> ComponentId {
1538 let type_id = TypeId::of::<T>();
1539 self.get_resource_id(type_id).unwrap_or_else(|| {
1540 // SAFETY: We just checked that this type was not in the queue.
1541 unsafe {
1542 self.force_register_arbitrary_resource(type_id, move |registrator, id| {
1543 // SAFETY: We just checked that this is not currently registered or queued, and if it was registered since, this would have been dropped from the queue.
1544 // SAFETY: Id uniqueness handled by caller, and the type_id matches descriptor.
1545 #[expect(unused_unsafe, reason = "More precise to specify.")]
1546 unsafe {
1547 registrator.register_resource_unchecked_with(type_id, id, || {
1548 ComponentDescriptor::new_non_send::<T>(StorageType::default())
1549 });
1550 }
1551 })
1552 }
1553 })
1554 }
1555
1556 /// This is a queued version of [`ComponentsRegistrator::register_resource_with_descriptor`].
1557 /// This will reserve an id and queue the registration.
1558 /// These registrations will be carried out at the next opportunity.
1559 ///
1560 /// # Note
1561 ///
1562 /// Technically speaking, the returned [`ComponentId`] is not valid, but it will become valid later.
1563 /// See type level docs for details.
1564 #[inline]
1565 pub fn queue_register_resource_with_descriptor(
1566 &self,
1567 descriptor: ComponentDescriptor,
1568 ) -> ComponentId {
1569 self.force_register_arbitrary_dynamic(|registrator, id| {
1570 // SAFETY: Id uniqueness handled by caller.
1571 unsafe {
1572 registrator.register_component_inner(id, descriptor);
1573 }
1574 })
1575 }
1576}
1577
1578/// A [`Components`] wrapper that enables additional features, like registration.
1579pub struct ComponentsRegistrator<'w> {
1580 components: &'w mut Components,
1581 ids: &'w mut ComponentIds,
1582}
1583
1584impl Deref for ComponentsRegistrator<'_> {
1585 type Target = Components;
1586
1587 fn deref(&self) -> &Self::Target {
1588 self.components
1589 }
1590}
1591
1592impl DerefMut for ComponentsRegistrator<'_> {
1593 fn deref_mut(&mut self) -> &mut Self::Target {
1594 self.components
1595 }
1596}
1597
1598impl<'w> ComponentsRegistrator<'w> {
1599 /// Constructs a new [`ComponentsRegistrator`].
1600 ///
1601 /// # Safety
1602 ///
1603 /// The [`Components`] and [`ComponentIds`] must match.
1604 /// For example, they must be from the same world.
1605 pub unsafe fn new(components: &'w mut Components, ids: &'w mut ComponentIds) -> Self {
1606 Self { components, ids }
1607 }
1608
1609 /// Converts this [`ComponentsRegistrator`] into a [`ComponentsQueuedRegistrator`].
1610 /// This is intended for use to pass this value to a function that requires [`ComponentsQueuedRegistrator`].
1611 /// It is generally not a good idea to queue a registration when you can instead register directly on this type.
1612 pub fn as_queued(&self) -> ComponentsQueuedRegistrator<'_> {
1613 // SAFETY: ensured by the caller that created self.
1614 unsafe { ComponentsQueuedRegistrator::new(self.components, self.ids) }
1615 }
1616
1617 /// Applies every queued registration.
1618 /// This ensures that every valid [`ComponentId`] is registered,
1619 /// enabling retrieving [`ComponentInfo`], etc.
1620 pub fn apply_queued_registrations(&mut self) {
1621 if !self.any_queued_mut() {
1622 return;
1623 }
1624
1625 // Note:
1626 //
1627 // This is not just draining the queue. We need to empty the queue without removing the information from `Components`.
1628 // If we drained directly, we could break invariance.
1629 //
1630 // For example, say `ComponentA` and `ComponentB` are queued, and `ComponentA` requires `ComponentB`.
1631 // If we drain directly, and `ComponentA` was the first to be registered, then, when `ComponentA`
1632 // registers `ComponentB` in `Component::register_required_components`,
1633 // `Components` will not know that `ComponentB` was queued
1634 // (since it will have been drained from the queue.)
1635 // If that happened, `Components` would assign a new `ComponentId` to `ComponentB`
1636 // which would be *different* than the id it was assigned in the queue.
1637 // Then, when the drain iterator gets to `ComponentB`,
1638 // it would be unsafely registering `ComponentB`, which is already registered.
1639 //
1640 // As a result, we need to pop from each queue one by one instead of draining.
1641
1642 // components
1643 while let Some(registrator) = {
1644 let queued = self
1645 .components
1646 .queued
1647 .get_mut()
1648 .unwrap_or_else(PoisonError::into_inner);
1649 queued.components.keys().next().copied().map(|type_id| {
1650 // SAFETY: the id just came from a valid iterator.
1651 unsafe { queued.components.remove(&type_id).debug_checked_unwrap() }
1652 })
1653 } {
1654 registrator.register(self);
1655 }
1656
1657 // resources
1658 while let Some(registrator) = {
1659 let queued = self
1660 .components
1661 .queued
1662 .get_mut()
1663 .unwrap_or_else(PoisonError::into_inner);
1664 queued.resources.keys().next().copied().map(|type_id| {
1665 // SAFETY: the id just came from a valid iterator.
1666 unsafe { queued.resources.remove(&type_id).debug_checked_unwrap() }
1667 })
1668 } {
1669 registrator.register(self);
1670 }
1671
1672 // dynamic
1673 let queued = &mut self
1674 .components
1675 .queued
1676 .get_mut()
1677 .unwrap_or_else(PoisonError::into_inner);
1678 if !queued.dynamic_registrations.is_empty() {
1679 for registrator in core::mem::take(&mut queued.dynamic_registrations) {
1680 registrator.register(self);
1681 }
1682 }
1683 }
1684
1685 /// Registers a [`Component`] of type `T` with this instance.
1686 /// If a component of this type has already been registered, this will return
1687 /// the ID of the pre-existing component.
1688 ///
1689 /// # See also
1690 ///
1691 /// * [`Components::component_id()`]
1692 /// * [`ComponentsRegistrator::register_component_with_descriptor()`]
1693 #[inline]
1694 pub fn register_component<T: Component>(&mut self) -> ComponentId {
1695 self.register_component_checked::<T>(&mut Vec::new())
1696 }
1697
1698 /// Same as [`Self::register_component_unchecked`] but keeps a checks for safety.
1699 #[inline]
1700 fn register_component_checked<T: Component>(
1701 &mut self,
1702 recursion_check_stack: &mut Vec<ComponentId>,
1703 ) -> ComponentId {
1704 let type_id = TypeId::of::<T>();
1705 if let Some(id) = self.indices.get(&type_id) {
1706 return *id;
1707 }
1708
1709 if let Some(registrator) = self
1710 .components
1711 .queued
1712 .get_mut()
1713 .unwrap_or_else(PoisonError::into_inner)
1714 .components
1715 .remove(&type_id)
1716 {
1717 // If we are trying to register something that has already been queued, we respect the queue.
1718 // Just like if we are trying to register something that already is, we respect the first registration.
1719 return registrator.register(self);
1720 }
1721
1722 let id = self.ids.next_mut();
1723 // SAFETY: The component is not currently registered, and the id is fresh.
1724 unsafe {
1725 self.register_component_unchecked::<T>(recursion_check_stack, id);
1726 }
1727 id
1728 }
1729
1730 /// # Safety
1731 ///
1732 /// Neither this component, nor its id may be registered or queued. This must be a new registration.
1733 #[inline]
1734 unsafe fn register_component_unchecked<T: Component>(
1735 &mut self,
1736 recursion_check_stack: &mut Vec<ComponentId>,
1737 id: ComponentId,
1738 ) {
1739 // SAFETY: ensured by caller.
1740 unsafe {
1741 self.register_component_inner(id, ComponentDescriptor::new::<T>());
1742 }
1743 let type_id = TypeId::of::<T>();
1744 let prev = self.indices.insert(type_id, id);
1745 debug_assert!(prev.is_none());
1746
1747 let mut required_components = RequiredComponents::default();
1748 T::register_required_components(
1749 id,
1750 self,
1751 &mut required_components,
1752 0,
1753 recursion_check_stack,
1754 );
1755 // SAFETY: we just inserted it in `register_component_inner`
1756 let info = unsafe {
1757 &mut self
1758 .components
1759 .components
1760 .get_mut(id.0)
1761 .debug_checked_unwrap()
1762 .as_mut()
1763 .debug_checked_unwrap()
1764 };
1765
1766 #[expect(
1767 deprecated,
1768 reason = "need to use this method until it is removed to ensure user defined components register hooks correctly"
1769 )]
1770 // TODO: Replace with `info.hooks.update_from_component::<T>();` once `Component::register_component_hooks` is removed
1771 T::register_component_hooks(&mut info.hooks);
1772
1773 info.required_components = required_components;
1774 }
1775
1776 /// Registers a component described by `descriptor`.
1777 ///
1778 /// # Note
1779 ///
1780 /// If this method is called multiple times with identical descriptors, a distinct [`ComponentId`]
1781 /// will be created for each one.
1782 ///
1783 /// # See also
1784 ///
1785 /// * [`Components::component_id()`]
1786 /// * [`ComponentsRegistrator::register_component()`]
1787 #[inline]
1788 pub fn register_component_with_descriptor(
1789 &mut self,
1790 descriptor: ComponentDescriptor,
1791 ) -> ComponentId {
1792 let id = self.ids.next_mut();
1793 // SAFETY: The id is fresh.
1794 unsafe {
1795 self.register_component_inner(id, descriptor);
1796 }
1797 id
1798 }
1799
1800 // NOTE: This should maybe be private, but it is currently public so that `bevy_ecs_macros` can use it.
1801 // We can't directly move this there either, because this uses `Components::get_required_by_mut`,
1802 // which is private, and could be equally risky to expose to users.
1803 /// Registers the given component `R` and [required components] inherited from it as required by `T`,
1804 /// and adds `T` to their lists of requirees.
1805 ///
1806 /// The given `inheritance_depth` determines how many levels of inheritance deep the requirement is.
1807 /// A direct requirement has a depth of `0`, and each level of inheritance increases the depth by `1`.
1808 /// Lower depths are more specific requirements, and can override existing less specific registrations.
1809 ///
1810 /// The `recursion_check_stack` allows checking whether this component tried to register itself as its
1811 /// own (indirect) required component.
1812 ///
1813 /// This method does *not* register any components as required by components that require `T`.
1814 ///
1815 /// Only use this method if you know what you are doing. In most cases, you should instead use [`World::register_required_components`],
1816 /// or the equivalent method in `bevy_app::App`.
1817 ///
1818 /// [required component]: Component#required-components
1819 #[doc(hidden)]
1820 pub fn register_required_components_manual<T: Component, R: Component>(
1821 &mut self,
1822 required_components: &mut RequiredComponents,
1823 constructor: fn() -> R,
1824 inheritance_depth: u16,
1825 recursion_check_stack: &mut Vec<ComponentId>,
1826 ) {
1827 let requiree = self.register_component_checked::<T>(recursion_check_stack);
1828 let required = self.register_component_checked::<R>(recursion_check_stack);
1829
1830 // SAFETY: We just created the components.
1831 unsafe {
1832 self.register_required_components_manual_unchecked::<R>(
1833 requiree,
1834 required,
1835 required_components,
1836 constructor,
1837 inheritance_depth,
1838 );
1839 }
1840 }
1841
1842 /// Registers a [`Resource`] of type `T` with this instance.
1843 /// If a resource of this type has already been registered, this will return
1844 /// the ID of the pre-existing resource.
1845 ///
1846 /// # See also
1847 ///
1848 /// * [`Components::resource_id()`]
1849 /// * [`ComponentsRegistrator::register_resource_with_descriptor()`]
1850 #[inline]
1851 pub fn register_resource<T: Resource>(&mut self) -> ComponentId {
1852 // SAFETY: The [`ComponentDescriptor`] matches the [`TypeId`]
1853 unsafe {
1854 self.register_resource_with(TypeId::of::<T>(), || {
1855 ComponentDescriptor::new_resource::<T>()
1856 })
1857 }
1858 }
1859
1860 /// Registers a [non-send resource](crate::system::NonSend) of type `T` with this instance.
1861 /// If a resource of this type has already been registered, this will return
1862 /// the ID of the pre-existing resource.
1863 #[inline]
1864 pub fn register_non_send<T: Any>(&mut self) -> ComponentId {
1865 // SAFETY: The [`ComponentDescriptor`] matches the [`TypeId`]
1866 unsafe {
1867 self.register_resource_with(TypeId::of::<T>(), || {
1868 ComponentDescriptor::new_non_send::<T>(StorageType::default())
1869 })
1870 }
1871 }
1872
1873 /// Same as [`Components::register_resource_unchecked_with`] but handles safety.
1874 ///
1875 /// # Safety
1876 ///
1877 /// The [`ComponentDescriptor`] must match the [`TypeId`].
1878 #[inline]
1879 unsafe fn register_resource_with(
1880 &mut self,
1881 type_id: TypeId,
1882 descriptor: impl FnOnce() -> ComponentDescriptor,
1883 ) -> ComponentId {
1884 if let Some(id) = self.resource_indices.get(&type_id) {
1885 return *id;
1886 }
1887
1888 if let Some(registrator) = self
1889 .components
1890 .queued
1891 .get_mut()
1892 .unwrap_or_else(PoisonError::into_inner)
1893 .resources
1894 .remove(&type_id)
1895 {
1896 // If we are trying to register something that has already been queued, we respect the queue.
1897 // Just like if we are trying to register something that already is, we respect the first registration.
1898 return registrator.register(self);
1899 }
1900
1901 let id = self.ids.next_mut();
1902 // SAFETY: The resource is not currently registered, the id is fresh, and the [`ComponentDescriptor`] matches the [`TypeId`]
1903 unsafe {
1904 self.register_resource_unchecked_with(type_id, id, descriptor);
1905 }
1906 id
1907 }
1908
1909 /// Registers a [`Resource`] described by `descriptor`.
1910 ///
1911 /// # Note
1912 ///
1913 /// If this method is called multiple times with identical descriptors, a distinct [`ComponentId`]
1914 /// will be created for each one.
1915 ///
1916 /// # See also
1917 ///
1918 /// * [`Components::resource_id()`]
1919 /// * [`ComponentsRegistrator::register_resource()`]
1920 #[inline]
1921 pub fn register_resource_with_descriptor(
1922 &mut self,
1923 descriptor: ComponentDescriptor,
1924 ) -> ComponentId {
1925 let id = self.ids.next_mut();
1926 // SAFETY: The id is fresh.
1927 unsafe {
1928 self.register_component_inner(id, descriptor);
1929 }
1930 id
1931 }
1932}
1933
1934/// Stores metadata associated with each kind of [`Component`] in a given [`World`].
1935#[derive(Debug, Default)]
1936pub struct Components {
1937 components: Vec<Option<ComponentInfo>>,
1938 indices: TypeIdMap<ComponentId>,
1939 resource_indices: TypeIdMap<ComponentId>,
1940 // This is kept internal and local to verify that no deadlocks can occor.
1941 queued: bevy_platform_support::sync::RwLock<QueuedComponents>,
1942}
1943
1944impl Components {
1945 /// This registers any descriptor, component or resource.
1946 ///
1947 /// # Safety
1948 ///
1949 /// The id must have never been registered before. This must be a fresh registration.
1950 #[inline]
1951 unsafe fn register_component_inner(
1952 &mut self,
1953 id: ComponentId,
1954 descriptor: ComponentDescriptor,
1955 ) {
1956 let info = ComponentInfo::new(id, descriptor);
1957 let least_len = id.0 + 1;
1958 if self.components.len() < least_len {
1959 self.components.resize_with(least_len, || None);
1960 }
1961 // SAFETY: We just extended the vec to make this index valid.
1962 let slot = unsafe { self.components.get_mut(id.0).debug_checked_unwrap() };
1963 // Caller ensures id is unique
1964 debug_assert!(slot.is_none());
1965 *slot = Some(info);
1966 }
1967
1968 /// Returns the number of components registered or queued with this instance.
1969 #[inline]
1970 pub fn len(&self) -> usize {
1971 self.num_queued() + self.num_registered()
1972 }
1973
1974 /// Returns `true` if there are no components registered or queued with this instance. Otherwise, this returns `false`.
1975 #[inline]
1976 pub fn is_empty(&self) -> bool {
1977 self.len() == 0
1978 }
1979
1980 /// Returns the number of components registered with this instance.
1981 #[inline]
1982 pub fn num_queued(&self) -> usize {
1983 let queued = self.queued.read().unwrap_or_else(PoisonError::into_inner);
1984 queued.components.len() + queued.dynamic_registrations.len() + queued.resources.len()
1985 }
1986
1987 /// Returns `true` if there are any components registered with this instance. Otherwise, this returns `false`.
1988 #[inline]
1989 pub fn any_queued(&self) -> bool {
1990 self.num_queued() > 0
1991 }
1992
1993 /// A faster version of [`Self::num_queued`].
1994 #[inline]
1995 pub fn num_queued_mut(&mut self) -> usize {
1996 let queued = self
1997 .queued
1998 .get_mut()
1999 .unwrap_or_else(PoisonError::into_inner);
2000 queued.components.len() + queued.dynamic_registrations.len() + queued.resources.len()
2001 }
2002
2003 /// A faster version of [`Self::any_queued`].
2004 #[inline]
2005 pub fn any_queued_mut(&mut self) -> bool {
2006 self.num_queued_mut() > 0
2007 }
2008
2009 /// Returns the number of components registered with this instance.
2010 #[inline]
2011 pub fn num_registered(&self) -> usize {
2012 self.components.len()
2013 }
2014
2015 /// Returns `true` if there are any components registered with this instance. Otherwise, this returns `false`.
2016 #[inline]
2017 pub fn any_registered(&self) -> bool {
2018 self.num_registered() > 0
2019 }
2020
2021 /// Gets the metadata associated with the given component, if it is registered.
2022 /// This will return `None` if the id is not regiserted or is queued.
2023 ///
2024 /// This will return an incorrect result if `id` did not come from the same world as `self`. It may return `None` or a garbage value.
2025 #[inline]
2026 pub fn get_info(&self, id: ComponentId) -> Option<&ComponentInfo> {
2027 self.components.get(id.0).and_then(|info| info.as_ref())
2028 }
2029
2030 /// Returns the name associated with the given component, if it is registered.
2031 /// This will return `None` if the id is not regiserted or is queued.
2032 ///
2033 /// This will return an incorrect result if `id` did not come from the same world as `self`. It may return `None` or a garbage value.
2034 #[inline]
2035 pub fn get_name(&self, id: ComponentId) -> Option<&str> {
2036 self.get_info(id).map(ComponentInfo::name)
2037 }
2038
2039 /// Gets the metadata associated with the given component.
2040 /// # Safety
2041 ///
2042 /// `id` must be a valid and fully registered [`ComponentId`].
2043 #[inline]
2044 pub unsafe fn get_info_unchecked(&self, id: ComponentId) -> &ComponentInfo {
2045 // SAFETY: The caller ensures `id` is valid.
2046 unsafe {
2047 self.components
2048 .get(id.0)
2049 .debug_checked_unwrap()
2050 .as_ref()
2051 .debug_checked_unwrap()
2052 }
2053 }
2054
2055 #[inline]
2056 pub(crate) fn get_hooks_mut(&mut self, id: ComponentId) -> Option<&mut ComponentHooks> {
2057 self.components
2058 .get_mut(id.0)
2059 .and_then(|info| info.as_mut().map(|info| &mut info.hooks))
2060 }
2061
2062 #[inline]
2063 pub(crate) fn get_required_components_mut(
2064 &mut self,
2065 id: ComponentId,
2066 ) -> Option<&mut RequiredComponents> {
2067 self.components
2068 .get_mut(id.0)
2069 .and_then(|info| info.as_mut().map(|info| &mut info.required_components))
2070 }
2071
2072 /// Registers the given component `R` and [required components] inherited from it as required by `T`.
2073 ///
2074 /// When `T` is added to an entity, `R` will also be added if it was not already provided.
2075 /// The given `constructor` will be used for the creation of `R`.
2076 ///
2077 /// [required components]: Component#required-components
2078 ///
2079 /// # Safety
2080 ///
2081 /// The given component IDs `required` and `requiree` must be valid.
2082 ///
2083 /// # Errors
2084 ///
2085 /// Returns a [`RequiredComponentsError`] if the `required` component is already a directly required component for the `requiree`.
2086 ///
2087 /// Indirect requirements through other components are allowed. In those cases, the more specific
2088 /// registration will be used.
2089 pub(crate) unsafe fn register_required_components<R: Component>(
2090 &mut self,
2091 requiree: ComponentId,
2092 required: ComponentId,
2093 constructor: fn() -> R,
2094 ) -> Result<(), RequiredComponentsError> {
2095 // SAFETY: The caller ensures that the `requiree` is valid.
2096 let required_components = unsafe {
2097 self.get_required_components_mut(requiree)
2098 .debug_checked_unwrap()
2099 };
2100
2101 // Cannot directly require the same component twice.
2102 if required_components
2103 .0
2104 .get(&required)
2105 .is_some_and(|c| c.inheritance_depth == 0)
2106 {
2107 return Err(RequiredComponentsError::DuplicateRegistration(
2108 requiree, required,
2109 ));
2110 }
2111
2112 // Register the required component for the requiree.
2113 // This is a direct requirement with a depth of `0`.
2114 required_components.register_by_id(required, constructor, 0);
2115
2116 // Add the requiree to the list of components that require the required component.
2117 // SAFETY: The component is in the list of required components, so it must exist already.
2118 let required_by = unsafe { self.get_required_by_mut(required).debug_checked_unwrap() };
2119 required_by.insert(requiree);
2120
2121 let mut required_components_tmp = RequiredComponents::default();
2122 // SAFETY: The caller ensures that the `requiree` and `required` components are valid.
2123 let inherited_requirements = unsafe {
2124 self.register_inherited_required_components(
2125 requiree,
2126 required,
2127 &mut required_components_tmp,
2128 )
2129 };
2130
2131 // SAFETY: The caller ensures that the `requiree` is valid.
2132 let required_components = unsafe {
2133 self.get_required_components_mut(requiree)
2134 .debug_checked_unwrap()
2135 };
2136 required_components.0.extend(required_components_tmp.0);
2137
2138 // Propagate the new required components up the chain to all components that require the requiree.
2139 if let Some(required_by) = self
2140 .get_required_by(requiree)
2141 .map(|set| set.iter().copied().collect::<SmallVec<[ComponentId; 8]>>())
2142 {
2143 // `required` is now required by anything that `requiree` was required by.
2144 self.get_required_by_mut(required)
2145 .unwrap()
2146 .extend(required_by.iter().copied());
2147 for &required_by_id in required_by.iter() {
2148 // SAFETY: The component is in the list of required components, so it must exist already.
2149 let required_components = unsafe {
2150 self.get_required_components_mut(required_by_id)
2151 .debug_checked_unwrap()
2152 };
2153
2154 // Register the original required component in the "parent" of the requiree.
2155 // The inheritance depth is 1 deeper than the `requiree` wrt `required_by_id`.
2156 let depth = required_components.0.get(&requiree).expect("requiree is required by required_by_id, so its required_components must include requiree").inheritance_depth;
2157 required_components.register_by_id(required, constructor, depth + 1);
2158
2159 for (component_id, component) in inherited_requirements.iter() {
2160 // Register the required component.
2161 // The inheritance depth of inherited components is whatever the requiree's
2162 // depth is relative to `required_by_id`, plus the inheritance depth of the
2163 // inherited component relative to the requiree, plus 1 to account for the
2164 // requiree in between.
2165 // SAFETY: Component ID and constructor match the ones on the original requiree.
2166 // The original requiree is responsible for making sure the registration is safe.
2167 unsafe {
2168 required_components.register_dynamic_with(
2169 *component_id,
2170 component.inheritance_depth + depth + 1,
2171 || component.constructor.clone(),
2172 );
2173 };
2174 }
2175 }
2176 }
2177
2178 Ok(())
2179 }
2180
2181 /// Registers the components inherited from `required` for the given `requiree`,
2182 /// returning the requirements in a list.
2183 ///
2184 /// # Safety
2185 ///
2186 /// The given component IDs `requiree` and `required` must be valid.
2187 unsafe fn register_inherited_required_components(
2188 &mut self,
2189 requiree: ComponentId,
2190 required: ComponentId,
2191 required_components: &mut RequiredComponents,
2192 ) -> Vec<(ComponentId, RequiredComponent)> {
2193 // Get required components inherited from the `required` component.
2194 // SAFETY: The caller ensures that the `required` component is valid.
2195 let required_component_info = unsafe { self.get_info(required).debug_checked_unwrap() };
2196 let inherited_requirements: Vec<(ComponentId, RequiredComponent)> = required_component_info
2197 .required_components()
2198 .0
2199 .iter()
2200 .map(|(component_id, required_component)| {
2201 (
2202 *component_id,
2203 RequiredComponent {
2204 constructor: required_component.constructor.clone(),
2205 // Add `1` to the inheritance depth since this will be registered
2206 // for the component that requires `required`.
2207 inheritance_depth: required_component.inheritance_depth + 1,
2208 },
2209 )
2210 })
2211 .collect();
2212
2213 // Register the new required components.
2214 for (component_id, component) in inherited_requirements.iter() {
2215 // Register the required component for the requiree.
2216 // SAFETY: Component ID and constructor match the ones on the original requiree.
2217 unsafe {
2218 required_components.register_dynamic_with(
2219 *component_id,
2220 component.inheritance_depth,
2221 || component.constructor.clone(),
2222 );
2223 };
2224
2225 // Add the requiree to the list of components that require the required component.
2226 // SAFETY: The caller ensures that the required components are valid.
2227 let required_by = unsafe {
2228 self.get_required_by_mut(*component_id)
2229 .debug_checked_unwrap()
2230 };
2231 required_by.insert(requiree);
2232 }
2233
2234 inherited_requirements
2235 }
2236
2237 /// Registers the given component `R` and [required components] inherited from it as required by `T`,
2238 /// and adds `T` to their lists of requirees.
2239 ///
2240 /// The given `inheritance_depth` determines how many levels of inheritance deep the requirement is.
2241 /// A direct requirement has a depth of `0`, and each level of inheritance increases the depth by `1`.
2242 /// Lower depths are more specific requirements, and can override existing less specific registrations.
2243 ///
2244 /// This method does *not* register any components as required by components that require `T`.
2245 ///
2246 /// [required component]: Component#required-components
2247 ///
2248 /// # Safety
2249 ///
2250 /// The given component IDs `required` and `requiree` must be valid.
2251 pub(crate) unsafe fn register_required_components_manual_unchecked<R: Component>(
2252 &mut self,
2253 requiree: ComponentId,
2254 required: ComponentId,
2255 required_components: &mut RequiredComponents,
2256 constructor: fn() -> R,
2257 inheritance_depth: u16,
2258 ) {
2259 // Components cannot require themselves.
2260 if required == requiree {
2261 return;
2262 }
2263
2264 // Register the required component `R` for the requiree.
2265 required_components.register_by_id(required, constructor, inheritance_depth);
2266
2267 // Add the requiree to the list of components that require `R`.
2268 // SAFETY: The caller ensures that the component ID is valid.
2269 // Assuming it is valid, the component is in the list of required components, so it must exist already.
2270 let required_by = unsafe { self.get_required_by_mut(required).debug_checked_unwrap() };
2271 required_by.insert(requiree);
2272
2273 self.register_inherited_required_components(requiree, required, required_components);
2274 }
2275
2276 #[inline]
2277 pub(crate) fn get_required_by(&self, id: ComponentId) -> Option<&HashSet<ComponentId>> {
2278 self.components
2279 .get(id.0)
2280 .and_then(|info| info.as_ref().map(|info| &info.required_by))
2281 }
2282
2283 #[inline]
2284 pub(crate) fn get_required_by_mut(
2285 &mut self,
2286 id: ComponentId,
2287 ) -> Option<&mut HashSet<ComponentId>> {
2288 self.components
2289 .get_mut(id.0)
2290 .and_then(|info| info.as_mut().map(|info| &mut info.required_by))
2291 }
2292
2293 /// Returns true if the [`ComponentId`] is fully registered and valid.
2294 /// Ids may be invalid if they are still queued to be registered.
2295 /// Those ids are still correct, but they are not usable in every context yet.
2296 #[inline]
2297 pub fn is_id_valid(&self, id: ComponentId) -> bool {
2298 self.components.get(id.0).is_some_and(Option::is_some)
2299 }
2300
2301 /// Type-erased equivalent of [`Components::valid_component_id()`].
2302 #[inline]
2303 pub fn get_valid_id(&self, type_id: TypeId) -> Option<ComponentId> {
2304 self.indices.get(&type_id).copied()
2305 }
2306
2307 /// Returns the [`ComponentId`] of the given [`Component`] type `T` if it is fully registered.
2308 /// If you want to include queued registration, see [`Components::component_id()`].
2309 ///
2310 /// ```
2311 /// use bevy_ecs::prelude::*;
2312 ///
2313 /// let mut world = World::new();
2314 ///
2315 /// #[derive(Component)]
2316 /// struct ComponentA;
2317 ///
2318 /// let component_a_id = world.register_component::<ComponentA>();
2319 ///
2320 /// assert_eq!(component_a_id, world.components().valid_component_id::<ComponentA>().unwrap())
2321 /// ```
2322 ///
2323 /// # See also
2324 ///
2325 /// * [`Components::get_valid_id()`]
2326 /// * [`Components::valid_resource_id()`]
2327 /// * [`World::component_id()`]
2328 #[inline]
2329 pub fn valid_component_id<T: Component>(&self) -> Option<ComponentId> {
2330 self.get_id(TypeId::of::<T>())
2331 }
2332
2333 /// Type-erased equivalent of [`Components::valid_resource_id()`].
2334 #[inline]
2335 pub fn get_valid_resource_id(&self, type_id: TypeId) -> Option<ComponentId> {
2336 self.resource_indices.get(&type_id).copied()
2337 }
2338
2339 /// Returns the [`ComponentId`] of the given [`Resource`] type `T` if it is fully registered.
2340 /// If you want to include queued registration, see [`Components::resource_id()`].
2341 ///
2342 /// ```
2343 /// use bevy_ecs::prelude::*;
2344 ///
2345 /// let mut world = World::new();
2346 ///
2347 /// #[derive(Resource, Default)]
2348 /// struct ResourceA;
2349 ///
2350 /// let resource_a_id = world.init_resource::<ResourceA>();
2351 ///
2352 /// assert_eq!(resource_a_id, world.components().valid_resource_id::<ResourceA>().unwrap())
2353 /// ```
2354 ///
2355 /// # See also
2356 ///
2357 /// * [`Components::valid_component_id()`]
2358 /// * [`Components::get_resource_id()`]
2359 #[inline]
2360 pub fn valid_resource_id<T: Resource>(&self) -> Option<ComponentId> {
2361 self.get_resource_id(TypeId::of::<T>())
2362 }
2363
2364 /// Type-erased equivalent of [`Components::component_id()`].
2365 #[inline]
2366 pub fn get_id(&self, type_id: TypeId) -> Option<ComponentId> {
2367 self.indices.get(&type_id).copied().or_else(|| {
2368 self.queued
2369 .read()
2370 .unwrap_or_else(PoisonError::into_inner)
2371 .components
2372 .get(&type_id)
2373 .map(|queued| queued.id)
2374 })
2375 }
2376
2377 /// Returns the [`ComponentId`] of the given [`Component`] type `T`.
2378 ///
2379 /// The returned `ComponentId` is specific to the `Components` instance
2380 /// it was retrieved from and should not be used with another `Components`
2381 /// instance.
2382 ///
2383 /// Returns [`None`] if the `Component` type has not
2384 /// yet been initialized using [`ComponentsRegistrator::register_component()`] or [`ComponentsQueuedRegistrator::queue_register_component()`].
2385 ///
2386 /// ```
2387 /// use bevy_ecs::prelude::*;
2388 ///
2389 /// let mut world = World::new();
2390 ///
2391 /// #[derive(Component)]
2392 /// struct ComponentA;
2393 ///
2394 /// let component_a_id = world.register_component::<ComponentA>();
2395 ///
2396 /// assert_eq!(component_a_id, world.components().component_id::<ComponentA>().unwrap())
2397 /// ```
2398 ///
2399 /// # See also
2400 ///
2401 /// * [`Components::get_id()`]
2402 /// * [`Components::resource_id()`]
2403 /// * [`World::component_id()`]
2404 #[inline]
2405 pub fn component_id<T: Component>(&self) -> Option<ComponentId> {
2406 self.get_id(TypeId::of::<T>())
2407 }
2408
2409 /// Type-erased equivalent of [`Components::resource_id()`].
2410 #[inline]
2411 pub fn get_resource_id(&self, type_id: TypeId) -> Option<ComponentId> {
2412 self.resource_indices.get(&type_id).copied().or_else(|| {
2413 self.queued
2414 .read()
2415 .unwrap_or_else(PoisonError::into_inner)
2416 .resources
2417 .get(&type_id)
2418 .map(|queued| queued.id)
2419 })
2420 }
2421
2422 /// Returns the [`ComponentId`] of the given [`Resource`] type `T`.
2423 ///
2424 /// The returned `ComponentId` is specific to the `Components` instance
2425 /// it was retrieved from and should not be used with another `Components`
2426 /// instance.
2427 ///
2428 /// Returns [`None`] if the `Resource` type has not
2429 /// yet been initialized using [`ComponentsRegistrator::register_resource()`] or [`ComponentsQueuedRegistrator::queue_register_resource()`].
2430 ///
2431 /// ```
2432 /// use bevy_ecs::prelude::*;
2433 ///
2434 /// let mut world = World::new();
2435 ///
2436 /// #[derive(Resource, Default)]
2437 /// struct ResourceA;
2438 ///
2439 /// let resource_a_id = world.init_resource::<ResourceA>();
2440 ///
2441 /// assert_eq!(resource_a_id, world.components().resource_id::<ResourceA>().unwrap())
2442 /// ```
2443 ///
2444 /// # See also
2445 ///
2446 /// * [`Components::component_id()`]
2447 /// * [`Components::get_resource_id()`]
2448 #[inline]
2449 pub fn resource_id<T: Resource>(&self) -> Option<ComponentId> {
2450 self.get_resource_id(TypeId::of::<T>())
2451 }
2452
2453 /// # Safety
2454 ///
2455 /// The [`ComponentDescriptor`] must match the [`TypeId`].
2456 /// The [`ComponentId`] must be unique.
2457 /// The [`TypeId`] and [`ComponentId`] must not be registered or queued.
2458 #[inline]
2459 unsafe fn register_resource_unchecked_with(
2460 &mut self,
2461 type_id: TypeId,
2462 component_id: ComponentId,
2463 func: impl FnOnce() -> ComponentDescriptor,
2464 ) {
2465 // SAFETY: ensured by caller
2466 unsafe {
2467 self.register_component_inner(component_id, func());
2468 }
2469 let prev = self.resource_indices.insert(type_id, component_id);
2470 debug_assert!(prev.is_none());
2471 }
2472
2473 /// Gets an iterator over all components fully registered with this instance.
2474 pub fn iter_registered(&self) -> impl Iterator<Item = &ComponentInfo> + '_ {
2475 self.components.iter().filter_map(Option::as_ref)
2476 }
2477}
2478
2479/// A value that tracks when a system ran relative to other systems.
2480/// This is used to power change detection.
2481///
2482/// *Note* that a system that hasn't been run yet has a `Tick` of 0.
2483#[derive(Copy, Clone, Default, Debug, Eq, Hash, PartialEq)]
2484#[cfg_attr(
2485 feature = "bevy_reflect",
2486 derive(Reflect),
2487 reflect(Debug, Hash, PartialEq, Clone)
2488)]
2489pub struct Tick {
2490 tick: u32,
2491}
2492
2493impl Tick {
2494 /// The maximum relative age for a change tick.
2495 /// The value of this is equal to [`MAX_CHANGE_AGE`].
2496 ///
2497 /// Since change detection will not work for any ticks older than this,
2498 /// ticks are periodically scanned to ensure their relative values are below this.
2499 pub const MAX: Self = Self::new(MAX_CHANGE_AGE);
2500
2501 /// Creates a new [`Tick`] wrapping the given value.
2502 #[inline]
2503 pub const fn new(tick: u32) -> Self {
2504 Self { tick }
2505 }
2506
2507 /// Gets the value of this change tick.
2508 #[inline]
2509 pub const fn get(self) -> u32 {
2510 self.tick
2511 }
2512
2513 /// Sets the value of this change tick.
2514 #[inline]
2515 pub fn set(&mut self, tick: u32) {
2516 self.tick = tick;
2517 }
2518
2519 /// Returns `true` if this `Tick` occurred since the system's `last_run`.
2520 ///
2521 /// `this_run` is the current tick of the system, used as a reference to help deal with wraparound.
2522 #[inline]
2523 pub fn is_newer_than(self, last_run: Tick, this_run: Tick) -> bool {
2524 // This works even with wraparound because the world tick (`this_run`) is always "newer" than
2525 // `last_run` and `self.tick`, and we scan periodically to clamp `ComponentTicks` values
2526 // so they never get older than `u32::MAX` (the difference would overflow).
2527 //
2528 // The clamp here ensures determinism (since scans could differ between app runs).
2529 let ticks_since_insert = this_run.relative_to(self).tick.min(MAX_CHANGE_AGE);
2530 let ticks_since_system = this_run.relative_to(last_run).tick.min(MAX_CHANGE_AGE);
2531
2532 ticks_since_system > ticks_since_insert
2533 }
2534
2535 /// Returns a change tick representing the relationship between `self` and `other`.
2536 #[inline]
2537 pub(crate) fn relative_to(self, other: Self) -> Self {
2538 let tick = self.tick.wrapping_sub(other.tick);
2539 Self { tick }
2540 }
2541
2542 /// Wraps this change tick's value if it exceeds [`Tick::MAX`].
2543 ///
2544 /// Returns `true` if wrapping was performed. Otherwise, returns `false`.
2545 #[inline]
2546 pub(crate) fn check_tick(&mut self, tick: Tick) -> bool {
2547 let age = tick.relative_to(*self);
2548 // This comparison assumes that `age` has not overflowed `u32::MAX` before, which will be true
2549 // so long as this check always runs before that can happen.
2550 if age.get() > Self::MAX.get() {
2551 *self = tick.relative_to(Self::MAX);
2552 true
2553 } else {
2554 false
2555 }
2556 }
2557}
2558
2559/// Interior-mutable access to the [`Tick`]s for a single component or resource.
2560#[derive(Copy, Clone, Debug)]
2561pub struct TickCells<'a> {
2562 /// The tick indicating when the value was added to the world.
2563 pub added: &'a UnsafeCell<Tick>,
2564 /// The tick indicating the last time the value was modified.
2565 pub changed: &'a UnsafeCell<Tick>,
2566}
2567
2568impl<'a> TickCells<'a> {
2569 /// # Safety
2570 /// All cells contained within must uphold the safety invariants of [`UnsafeCellDeref::read`].
2571 #[inline]
2572 pub(crate) unsafe fn read(&self) -> ComponentTicks {
2573 ComponentTicks {
2574 // SAFETY: The callers uphold the invariants for `read`.
2575 added: unsafe { self.added.read() },
2576 // SAFETY: The callers uphold the invariants for `read`.
2577 changed: unsafe { self.changed.read() },
2578 }
2579 }
2580}
2581
2582/// Records when a component or resource was added and when it was last mutably dereferenced (or added).
2583#[derive(Copy, Clone, Debug)]
2584#[cfg_attr(feature = "bevy_reflect", derive(Reflect), reflect(Debug, Clone))]
2585pub struct ComponentTicks {
2586 /// Tick recording the time this component or resource was added.
2587 pub added: Tick,
2588
2589 /// Tick recording the time this component or resource was most recently changed.
2590 pub changed: Tick,
2591}
2592
2593impl ComponentTicks {
2594 /// Returns `true` if the component or resource was added after the system last ran
2595 /// (or the system is running for the first time).
2596 #[inline]
2597 pub fn is_added(&self, last_run: Tick, this_run: Tick) -> bool {
2598 self.added.is_newer_than(last_run, this_run)
2599 }
2600
2601 /// Returns `true` if the component or resource was added or mutably dereferenced after the system last ran
2602 /// (or the system is running for the first time).
2603 #[inline]
2604 pub fn is_changed(&self, last_run: Tick, this_run: Tick) -> bool {
2605 self.changed.is_newer_than(last_run, this_run)
2606 }
2607
2608 /// Creates a new instance with the same change tick for `added` and `changed`.
2609 pub fn new(change_tick: Tick) -> Self {
2610 Self {
2611 added: change_tick,
2612 changed: change_tick,
2613 }
2614 }
2615
2616 /// Manually sets the change tick.
2617 ///
2618 /// This is normally done automatically via the [`DerefMut`] implementation
2619 /// on [`Mut<T>`](crate::change_detection::Mut), [`ResMut<T>`](crate::change_detection::ResMut), etc.
2620 /// However, components and resources that make use of interior mutability might require manual updates.
2621 ///
2622 /// # Example
2623 /// ```no_run
2624 /// # use bevy_ecs::{world::World, component::ComponentTicks};
2625 /// let world: World = unimplemented!();
2626 /// let component_ticks: ComponentTicks = unimplemented!();
2627 ///
2628 /// component_ticks.set_changed(world.read_change_tick());
2629 /// ```
2630 #[inline]
2631 pub fn set_changed(&mut self, change_tick: Tick) {
2632 self.changed = change_tick;
2633 }
2634}
2635
2636/// A [`SystemParam`] that provides access to the [`ComponentId`] for a specific component type.
2637///
2638/// # Example
2639/// ```
2640/// # use bevy_ecs::{system::Local, component::{Component, ComponentId, ComponentIdFor}};
2641/// #[derive(Component)]
2642/// struct Player;
2643/// fn my_system(component_id: ComponentIdFor<Player>) {
2644/// let component_id: ComponentId = component_id.get();
2645/// // ...
2646/// }
2647/// ```
2648#[derive(SystemParam)]
2649pub struct ComponentIdFor<'s, T: Component>(Local<'s, InitComponentId<T>>);
2650
2651impl<T: Component> ComponentIdFor<'_, T> {
2652 /// Gets the [`ComponentId`] for the type `T`.
2653 #[inline]
2654 pub fn get(&self) -> ComponentId {
2655 **self
2656 }
2657}
2658
2659impl<T: Component> Deref for ComponentIdFor<'_, T> {
2660 type Target = ComponentId;
2661 fn deref(&self) -> &Self::Target {
2662 &self.0.component_id
2663 }
2664}
2665
2666impl<T: Component> From<ComponentIdFor<'_, T>> for ComponentId {
2667 #[inline]
2668 fn from(to_component_id: ComponentIdFor<T>) -> ComponentId {
2669 *to_component_id
2670 }
2671}
2672
2673/// Initializes the [`ComponentId`] for a specific type when used with [`FromWorld`].
2674struct InitComponentId<T: Component> {
2675 component_id: ComponentId,
2676 marker: PhantomData<T>,
2677}
2678
2679impl<T: Component> FromWorld for InitComponentId<T> {
2680 fn from_world(world: &mut World) -> Self {
2681 Self {
2682 component_id: world.register_component::<T>(),
2683 marker: PhantomData,
2684 }
2685 }
2686}
2687
2688/// An error returned when the registration of a required component fails.
2689#[derive(Error, Debug)]
2690#[non_exhaustive]
2691pub enum RequiredComponentsError {
2692 /// The component is already a directly required component for the requiree.
2693 #[error("Component {0:?} already directly requires component {1:?}")]
2694 DuplicateRegistration(ComponentId, ComponentId),
2695 /// An archetype with the component that requires other components already exists
2696 #[error("An archetype with the component {0:?} that requires other components already exists")]
2697 ArchetypeExists(ComponentId),
2698}
2699
2700/// A Required Component constructor. See [`Component`] for details.
2701#[derive(Clone)]
2702pub struct RequiredComponentConstructor(
2703 pub Arc<dyn Fn(&mut Table, &mut SparseSets, Tick, TableRow, Entity, MaybeLocation)>,
2704);
2705
2706impl RequiredComponentConstructor {
2707 /// # Safety
2708 /// This is intended to only be called in the context of [`BundleInfo::write_components`] to initialized required components.
2709 /// Calling it _anywhere else_ should be considered unsafe.
2710 ///
2711 /// `table_row` and `entity` must correspond to a valid entity that currently needs a component initialized via the constructor stored
2712 /// on this [`RequiredComponentConstructor`]. The stored constructor must correspond to a component on `entity` that needs initialization.
2713 /// `table` and `sparse_sets` must correspond to storages on a world where `entity` needs this required component initialized.
2714 ///
2715 /// Again, don't call this anywhere but [`BundleInfo::write_components`].
2716 pub(crate) unsafe fn initialize(
2717 &self,
2718 table: &mut Table,
2719 sparse_sets: &mut SparseSets,
2720 change_tick: Tick,
2721 table_row: TableRow,
2722 entity: Entity,
2723 caller: MaybeLocation,
2724 ) {
2725 (self.0)(table, sparse_sets, change_tick, table_row, entity, caller);
2726 }
2727}
2728
2729/// Metadata associated with a required component. See [`Component`] for details.
2730#[derive(Clone)]
2731pub struct RequiredComponent {
2732 /// The constructor used for the required component.
2733 pub constructor: RequiredComponentConstructor,
2734
2735 /// The depth of the component requirement in the requirement hierarchy for this component.
2736 /// This is used for determining which constructor is used in cases where there are duplicate requires.
2737 ///
2738 /// For example, consider the inheritance tree `X -> Y -> Z`, where `->` indicates a requirement.
2739 /// `X -> Y` and `Y -> Z` are direct requirements with a depth of 0, while `Z` is only indirectly
2740 /// required for `X` with a depth of `1`.
2741 ///
2742 /// In cases where there are multiple conflicting requirements with the same depth, a higher priority
2743 /// will be given to components listed earlier in the `require` attribute, or to the latest added requirement
2744 /// if registered at runtime.
2745 pub inheritance_depth: u16,
2746}
2747
2748/// The collection of metadata for components that are required for a given component.
2749///
2750/// For more information, see the "Required Components" section of [`Component`].
2751#[derive(Default, Clone)]
2752pub struct RequiredComponents(pub(crate) HashMap<ComponentId, RequiredComponent>);
2753
2754impl Debug for RequiredComponents {
2755 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2756 f.debug_tuple("RequiredComponents")
2757 .field(&self.0.keys())
2758 .finish()
2759 }
2760}
2761
2762impl RequiredComponents {
2763 /// Registers a required component.
2764 ///
2765 /// If the component is already registered, it will be overwritten if the given inheritance depth
2766 /// is smaller than the depth of the existing registration. Otherwise, the new registration will be ignored.
2767 ///
2768 /// # Safety
2769 ///
2770 /// `component_id` must match the type initialized by `constructor`.
2771 /// `constructor` _must_ initialize a component for `component_id` in such a way that
2772 /// matches the storage type of the component. It must only use the given `table_row` or `Entity` to
2773 /// initialize the storage for `component_id` corresponding to the given entity.
2774 pub unsafe fn register_dynamic_with(
2775 &mut self,
2776 component_id: ComponentId,
2777 inheritance_depth: u16,
2778 constructor: impl FnOnce() -> RequiredComponentConstructor,
2779 ) {
2780 let entry = self.0.entry(component_id);
2781 match entry {
2782 bevy_platform_support::collections::hash_map::Entry::Occupied(mut occupied) => {
2783 let current = occupied.get_mut();
2784 if current.inheritance_depth > inheritance_depth {
2785 *current = RequiredComponent {
2786 constructor: constructor(),
2787 inheritance_depth,
2788 }
2789 }
2790 }
2791 bevy_platform_support::collections::hash_map::Entry::Vacant(vacant) => {
2792 vacant.insert(RequiredComponent {
2793 constructor: constructor(),
2794 inheritance_depth,
2795 });
2796 }
2797 }
2798 }
2799
2800 /// Registers a required component.
2801 ///
2802 /// If the component is already registered, it will be overwritten if the given inheritance depth
2803 /// is smaller than the depth of the existing registration. Otherwise, the new registration will be ignored.
2804 pub fn register<C: Component>(
2805 &mut self,
2806 components: &mut ComponentsRegistrator,
2807 constructor: fn() -> C,
2808 inheritance_depth: u16,
2809 ) {
2810 let component_id = components.register_component::<C>();
2811 self.register_by_id(component_id, constructor, inheritance_depth);
2812 }
2813
2814 /// Registers the [`Component`] with the given ID as required if it exists.
2815 ///
2816 /// If the component is already registered, it will be overwritten if the given inheritance depth
2817 /// is smaller than the depth of the existing registration. Otherwise, the new registration will be ignored.
2818 pub fn register_by_id<C: Component>(
2819 &mut self,
2820 component_id: ComponentId,
2821 constructor: fn() -> C,
2822 inheritance_depth: u16,
2823 ) {
2824 let erased = || {
2825 RequiredComponentConstructor({
2826 // `portable-atomic-util` `Arc` is not able to coerce an unsized
2827 // type like `std::sync::Arc` can. Creating a `Box` first does the
2828 // coercion.
2829 //
2830 // This would be resolved by https://github.com/rust-lang/rust/issues/123430
2831
2832 #[cfg(not(target_has_atomic = "ptr"))]
2833 use alloc::boxed::Box;
2834
2835 type Constructor = dyn for<'a, 'b> Fn(
2836 &'a mut Table,
2837 &'b mut SparseSets,
2838 Tick,
2839 TableRow,
2840 Entity,
2841 MaybeLocation,
2842 );
2843
2844 #[cfg(not(target_has_atomic = "ptr"))]
2845 type Intermediate<T> = Box<T>;
2846
2847 #[cfg(target_has_atomic = "ptr")]
2848 type Intermediate<T> = Arc<T>;
2849
2850 let boxed: Intermediate<Constructor> = Intermediate::new(
2851 move |table, sparse_sets, change_tick, table_row, entity, caller| {
2852 OwningPtr::make(constructor(), |ptr| {
2853 // SAFETY: This will only be called in the context of `BundleInfo::write_components`, which will
2854 // pass in a valid table_row and entity requiring a C constructor
2855 // C::STORAGE_TYPE is the storage type associated with `component_id` / `C`
2856 // `ptr` points to valid `C` data, which matches the type associated with `component_id`
2857 unsafe {
2858 BundleInfo::initialize_required_component(
2859 table,
2860 sparse_sets,
2861 change_tick,
2862 table_row,
2863 entity,
2864 component_id,
2865 C::STORAGE_TYPE,
2866 ptr,
2867 caller,
2868 );
2869 }
2870 });
2871 },
2872 );
2873
2874 Arc::from(boxed)
2875 })
2876 };
2877
2878 // SAFETY:
2879 // `component_id` matches the type initialized by the `erased` constructor above.
2880 // `erased` initializes a component for `component_id` in such a way that
2881 // matches the storage type of the component. It only uses the given `table_row` or `Entity` to
2882 // initialize the storage corresponding to the given entity.
2883 unsafe { self.register_dynamic_with(component_id, inheritance_depth, erased) };
2884 }
2885
2886 /// Iterates the ids of all required components. This includes recursive required components.
2887 pub fn iter_ids(&self) -> impl Iterator<Item = ComponentId> + '_ {
2888 self.0.keys().copied()
2889 }
2890
2891 /// Removes components that are explicitly provided in a given [`Bundle`]. These components should
2892 /// be logically treated as normal components, not "required components".
2893 ///
2894 /// [`Bundle`]: crate::bundle::Bundle
2895 pub(crate) fn remove_explicit_components(&mut self, components: &[ComponentId]) {
2896 for component in components {
2897 self.0.remove(component);
2898 }
2899 }
2900
2901 /// Merges `required_components` into this collection. This only inserts a required component
2902 /// if it _did not already exist_ *or* if the required component is more specific than the existing one
2903 /// (in other words, if the inheritance depth is smaller).
2904 ///
2905 /// See [`register_dynamic_with`](Self::register_dynamic_with) for details.
2906 pub(crate) fn merge(&mut self, required_components: &RequiredComponents) {
2907 for (
2908 component_id,
2909 RequiredComponent {
2910 constructor,
2911 inheritance_depth,
2912 },
2913 ) in required_components.0.iter()
2914 {
2915 // SAFETY: This exact registration must have been done on `required_components`, so safety is ensured by that caller.
2916 unsafe {
2917 self.register_dynamic_with(*component_id, *inheritance_depth, || {
2918 constructor.clone()
2919 });
2920 }
2921 }
2922 }
2923}
2924
2925// NOTE: This should maybe be private, but it is currently public so that `bevy_ecs_macros` can use it.
2926// This exists as a standalone function instead of being inlined into the component derive macro so as
2927// to reduce the amount of generated code.
2928#[doc(hidden)]
2929pub fn enforce_no_required_components_recursion(
2930 components: &Components,
2931 recursion_check_stack: &[ComponentId],
2932) {
2933 if let Some((&requiree, check)) = recursion_check_stack.split_last() {
2934 if let Some(direct_recursion) = check
2935 .iter()
2936 .position(|&id| id == requiree)
2937 .map(|index| index == check.len() - 1)
2938 {
2939 panic!(
2940 "Recursive required components detected: {}\nhelp: {}",
2941 recursion_check_stack
2942 .iter()
2943 .map(|id| format!("{}", ShortName(components.get_name(*id).unwrap())))
2944 .collect::<Vec<_>>()
2945 .join(" → "),
2946 if direct_recursion {
2947 format!(
2948 "Remove require({}).",
2949 ShortName(components.get_name(requiree).unwrap())
2950 )
2951 } else {
2952 "If this is intentional, consider merging the components.".into()
2953 }
2954 );
2955 }
2956 }
2957}
2958
2959/// Component [clone handler function](ComponentCloneFn) implemented using the [`Clone`] trait.
2960/// Can be [set](Component::clone_behavior) as clone handler for the specific component it is implemented for.
2961/// It will panic if set as handler for any other component.
2962///
2963pub fn component_clone_via_clone<C: Clone + Component>(
2964 source: &SourceComponent,
2965 ctx: &mut ComponentCloneCtx,
2966) {
2967 if let Some(component) = source.read::<C>() {
2968 ctx.write_target_component(component.clone());
2969 }
2970}
2971
2972/// Component [clone handler function](ComponentCloneFn) implemented using reflect.
2973/// Can be [set](Component::clone_behavior) as clone handler for any registered component,
2974/// but only reflected components will be cloned.
2975///
2976/// To clone a component using this handler, the following must be true:
2977/// - World has [`AppTypeRegistry`](crate::reflect::AppTypeRegistry)
2978/// - Component has [`TypeId`]
2979/// - Component is registered
2980/// - Component has [`ReflectFromPtr`](bevy_reflect::ReflectFromPtr) registered
2981/// - Component can be cloned via [`PartialReflect::reflect_clone`] _or_ has one of the following registered: [`ReflectFromReflect`](bevy_reflect::ReflectFromReflect),
2982/// [`ReflectDefault`](bevy_reflect::std_traits::ReflectDefault), [`ReflectFromWorld`](crate::reflect::ReflectFromWorld)
2983///
2984/// If any of the conditions is not satisfied, the component will be skipped.
2985///
2986/// See [`EntityClonerBuilder`](crate::entity::EntityClonerBuilder) for details.
2987///
2988/// [`PartialReflect::reflect_clone`]: bevy_reflect::PartialReflect::reflect_clone
2989#[cfg(feature = "bevy_reflect")]
2990pub fn component_clone_via_reflect(source: &SourceComponent, ctx: &mut ComponentCloneCtx) {
2991 let Some(app_registry) = ctx.type_registry().cloned() else {
2992 return;
2993 };
2994 let registry = app_registry.read();
2995 let Some(source_component_reflect) = source.read_reflect(®istry) else {
2996 return;
2997 };
2998 let component_info = ctx.component_info();
2999 // checked in read_source_component_reflect
3000 let type_id = component_info.type_id().unwrap();
3001
3002 // Try to clone using `reflect_clone`
3003 if let Ok(mut component) = source_component_reflect.reflect_clone() {
3004 if let Some(reflect_component) =
3005 registry.get_type_data::<crate::reflect::ReflectComponent>(type_id)
3006 {
3007 reflect_component.map_entities(&mut *component, ctx.entity_mapper());
3008 }
3009 drop(registry);
3010
3011 ctx.write_target_component_reflect(component);
3012 return;
3013 }
3014
3015 // Try to clone using ReflectFromReflect
3016 if let Some(reflect_from_reflect) =
3017 registry.get_type_data::<bevy_reflect::ReflectFromReflect>(type_id)
3018 {
3019 if let Some(mut component) =
3020 reflect_from_reflect.from_reflect(source_component_reflect.as_partial_reflect())
3021 {
3022 if let Some(reflect_component) =
3023 registry.get_type_data::<crate::reflect::ReflectComponent>(type_id)
3024 {
3025 reflect_component.map_entities(&mut *component, ctx.entity_mapper());
3026 }
3027 drop(registry);
3028
3029 ctx.write_target_component_reflect(component);
3030 return;
3031 }
3032 }
3033 // Else, try to clone using ReflectDefault
3034 if let Some(reflect_default) =
3035 registry.get_type_data::<bevy_reflect::std_traits::ReflectDefault>(type_id)
3036 {
3037 let mut component = reflect_default.default();
3038 component.apply(source_component_reflect.as_partial_reflect());
3039 drop(registry);
3040 ctx.write_target_component_reflect(component);
3041 return;
3042 }
3043 // Otherwise, try to clone using ReflectFromWorld
3044 if let Some(reflect_from_world) =
3045 registry.get_type_data::<crate::reflect::ReflectFromWorld>(type_id)
3046 {
3047 let reflect_from_world = reflect_from_world.clone();
3048 let source_component_cloned = source_component_reflect.to_dynamic();
3049 let component_layout = component_info.layout();
3050 let target = ctx.target();
3051 let component_id = ctx.component_id();
3052 drop(registry);
3053 ctx.queue_deferred(move |world: &mut World, mapper: &mut dyn EntityMapper| {
3054 let mut component = reflect_from_world.from_world(world);
3055 assert_eq!(type_id, (*component).type_id());
3056 component.apply(source_component_cloned.as_partial_reflect());
3057 if let Some(reflect_component) = app_registry
3058 .read()
3059 .get_type_data::<crate::reflect::ReflectComponent>(type_id)
3060 {
3061 reflect_component.map_entities(&mut *component, mapper);
3062 }
3063 // SAFETY:
3064 // - component_id is from the same world as target entity
3065 // - component is a valid value represented by component_id
3066 unsafe {
3067 let raw_component_ptr =
3068 core::ptr::NonNull::new_unchecked(Box::into_raw(component).cast::<u8>());
3069 world
3070 .entity_mut(target)
3071 .insert_by_id(component_id, OwningPtr::new(raw_component_ptr));
3072
3073 if component_layout.size() > 0 {
3074 // Ensure we don't attempt to deallocate zero-sized components
3075 alloc::alloc::dealloc(raw_component_ptr.as_ptr(), component_layout);
3076 }
3077 }
3078 });
3079 }
3080}
3081
3082/// Noop implementation of component clone handler function.
3083///
3084/// See [`EntityClonerBuilder`](crate::entity::EntityClonerBuilder) for details.
3085pub fn component_clone_ignore(_source: &SourceComponent, _ctx: &mut ComponentCloneCtx) {}
3086
3087/// Wrapper for components clone specialization using autoderef.
3088#[doc(hidden)]
3089pub struct DefaultCloneBehaviorSpecialization<T>(PhantomData<T>);
3090
3091impl<T> Default for DefaultCloneBehaviorSpecialization<T> {
3092 fn default() -> Self {
3093 Self(PhantomData)
3094 }
3095}
3096
3097/// Base trait for components clone specialization using autoderef.
3098#[doc(hidden)]
3099pub trait DefaultCloneBehaviorBase {
3100 fn default_clone_behavior(&self) -> ComponentCloneBehavior;
3101}
3102impl<C> DefaultCloneBehaviorBase for DefaultCloneBehaviorSpecialization<C> {
3103 fn default_clone_behavior(&self) -> ComponentCloneBehavior {
3104 ComponentCloneBehavior::Default
3105 }
3106}
3107
3108/// Specialized trait for components clone specialization using autoderef.
3109#[doc(hidden)]
3110pub trait DefaultCloneBehaviorViaClone {
3111 fn default_clone_behavior(&self) -> ComponentCloneBehavior;
3112}
3113impl<C: Clone + Component> DefaultCloneBehaviorViaClone for &DefaultCloneBehaviorSpecialization<C> {
3114 fn default_clone_behavior(&self) -> ComponentCloneBehavior {
3115 ComponentCloneBehavior::clone::<C>()
3116 }
3117}