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::sync::Arc;
19use bevy_platform::{
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::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, ComponentDescriptor)>,
1247 id: ComponentId,
1248 descriptor: ComponentDescriptor,
1249}
1250
1251impl QueuedRegistration {
1252 /// Creates the [`QueuedRegistration`].
1253 ///
1254 /// # Safety
1255 ///
1256 /// [`ComponentId`] must be unique.
1257 unsafe fn new(
1258 id: ComponentId,
1259 descriptor: ComponentDescriptor,
1260 func: impl FnOnce(&mut ComponentsRegistrator, ComponentId, ComponentDescriptor) + 'static,
1261 ) -> Self {
1262 Self {
1263 registrator: Box::new(func),
1264 id,
1265 descriptor,
1266 }
1267 }
1268
1269 /// Performs the registration, returning the now valid [`ComponentId`].
1270 fn register(self, registrator: &mut ComponentsRegistrator) -> ComponentId {
1271 (self.registrator)(registrator, self.id, self.descriptor);
1272 self.id
1273 }
1274}
1275
1276/// Allows queuing components to be registered.
1277#[derive(Default)]
1278pub struct QueuedComponents {
1279 components: TypeIdMap<QueuedRegistration>,
1280 resources: TypeIdMap<QueuedRegistration>,
1281 dynamic_registrations: Vec<QueuedRegistration>,
1282}
1283
1284impl Debug for QueuedComponents {
1285 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1286 let components = self
1287 .components
1288 .iter()
1289 .map(|(type_id, queued)| (type_id, queued.id))
1290 .collect::<Vec<_>>();
1291 let resources = self
1292 .resources
1293 .iter()
1294 .map(|(type_id, queued)| (type_id, queued.id))
1295 .collect::<Vec<_>>();
1296 let dynamic_registrations = self
1297 .dynamic_registrations
1298 .iter()
1299 .map(|queued| queued.id)
1300 .collect::<Vec<_>>();
1301 write!(f, "components: {components:?}, resources: {resources:?}, dynamic_registrations: {dynamic_registrations:?}")
1302 }
1303}
1304
1305/// Generates [`ComponentId`]s.
1306#[derive(Debug, Default)]
1307pub struct ComponentIds {
1308 next: bevy_platform::sync::atomic::AtomicUsize,
1309}
1310
1311impl ComponentIds {
1312 /// Peeks the next [`ComponentId`] to be generated without generating it.
1313 pub fn peek(&self) -> ComponentId {
1314 ComponentId(
1315 self.next
1316 .load(bevy_platform::sync::atomic::Ordering::Relaxed),
1317 )
1318 }
1319
1320 /// Generates and returns the next [`ComponentId`].
1321 pub fn next(&self) -> ComponentId {
1322 ComponentId(
1323 self.next
1324 .fetch_add(1, bevy_platform::sync::atomic::Ordering::Relaxed),
1325 )
1326 }
1327
1328 /// Peeks the next [`ComponentId`] to be generated without generating it.
1329 pub fn peek_mut(&mut self) -> ComponentId {
1330 ComponentId(*self.next.get_mut())
1331 }
1332
1333 /// Generates and returns the next [`ComponentId`].
1334 pub fn next_mut(&mut self) -> ComponentId {
1335 let id = self.next.get_mut();
1336 let result = ComponentId(*id);
1337 *id += 1;
1338 result
1339 }
1340
1341 /// Returns the number of [`ComponentId`]s generated.
1342 pub fn len(&self) -> usize {
1343 self.peek().0
1344 }
1345
1346 /// Returns true if and only if no ids have been generated.
1347 pub fn is_empty(&self) -> bool {
1348 self.len() == 0
1349 }
1350}
1351
1352/// A type that enables queuing registration in [`Components`].
1353///
1354/// # Note
1355///
1356/// These queued registrations return [`ComponentId`]s.
1357/// These ids are not yet valid, but they will become valid
1358/// when either [`ComponentsRegistrator::apply_queued_registrations`] is called or the same registration is made directly.
1359/// In either case, the returned [`ComponentId`]s will be correct, but they are not correct yet.
1360///
1361/// Generally, that means these [`ComponentId`]s can be safely used for read-only purposes.
1362/// Modifying the contents of the world through these [`ComponentId`]s directly without waiting for them to be fully registered
1363/// and without then confirming that they have been fully registered is not supported.
1364/// Hence, extra care is needed with these [`ComponentId`]s to ensure all safety rules are followed.
1365///
1366/// As a rule of thumb, if you have mutable access to [`ComponentsRegistrator`], prefer to use that instead.
1367/// 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.
1368#[derive(Clone, Copy)]
1369pub struct ComponentsQueuedRegistrator<'w> {
1370 components: &'w Components,
1371 ids: &'w ComponentIds,
1372}
1373
1374impl Deref for ComponentsQueuedRegistrator<'_> {
1375 type Target = Components;
1376
1377 fn deref(&self) -> &Self::Target {
1378 self.components
1379 }
1380}
1381
1382impl<'w> ComponentsQueuedRegistrator<'w> {
1383 /// Constructs a new [`ComponentsQueuedRegistrator`].
1384 ///
1385 /// # Safety
1386 ///
1387 /// The [`Components`] and [`ComponentIds`] must match.
1388 /// For example, they must be from the same world.
1389 pub unsafe fn new(components: &'w Components, ids: &'w ComponentIds) -> Self {
1390 Self { components, ids }
1391 }
1392
1393 /// Queues this function to run as a component registrator.
1394 ///
1395 /// # Safety
1396 ///
1397 /// The [`TypeId`] must not already be registered or queued as a component.
1398 unsafe fn force_register_arbitrary_component(
1399 &self,
1400 type_id: TypeId,
1401 descriptor: ComponentDescriptor,
1402 func: impl FnOnce(&mut ComponentsRegistrator, ComponentId, ComponentDescriptor) + 'static,
1403 ) -> ComponentId {
1404 let id = self.ids.next();
1405 self.components
1406 .queued
1407 .write()
1408 .unwrap_or_else(PoisonError::into_inner)
1409 .components
1410 .insert(
1411 type_id,
1412 // SAFETY: The id was just generated.
1413 unsafe { QueuedRegistration::new(id, descriptor, func) },
1414 );
1415 id
1416 }
1417
1418 /// Queues this function to run as a resource registrator.
1419 ///
1420 /// # Safety
1421 ///
1422 /// The [`TypeId`] must not already be registered or queued as a resource.
1423 unsafe fn force_register_arbitrary_resource(
1424 &self,
1425 type_id: TypeId,
1426 descriptor: ComponentDescriptor,
1427 func: impl FnOnce(&mut ComponentsRegistrator, ComponentId, ComponentDescriptor) + 'static,
1428 ) -> ComponentId {
1429 let id = self.ids.next();
1430 self.components
1431 .queued
1432 .write()
1433 .unwrap_or_else(PoisonError::into_inner)
1434 .resources
1435 .insert(
1436 type_id,
1437 // SAFETY: The id was just generated.
1438 unsafe { QueuedRegistration::new(id, descriptor, func) },
1439 );
1440 id
1441 }
1442
1443 /// Queues this function to run as a dynamic registrator.
1444 fn force_register_arbitrary_dynamic(
1445 &self,
1446 descriptor: ComponentDescriptor,
1447 func: impl FnOnce(&mut ComponentsRegistrator, ComponentId, ComponentDescriptor) + 'static,
1448 ) -> ComponentId {
1449 let id = self.ids.next();
1450 self.components
1451 .queued
1452 .write()
1453 .unwrap_or_else(PoisonError::into_inner)
1454 .dynamic_registrations
1455 .push(
1456 // SAFETY: The id was just generated.
1457 unsafe { QueuedRegistration::new(id, descriptor, func) },
1458 );
1459 id
1460 }
1461
1462 /// This is a queued version of [`ComponentsRegistrator::register_component`].
1463 /// This will reserve an id and queue the registration.
1464 /// These registrations will be carried out at the next opportunity.
1465 ///
1466 /// If this has already been registered or queued, this returns the previous [`ComponentId`].
1467 ///
1468 /// # Note
1469 ///
1470 /// Technically speaking, the returned [`ComponentId`] is not valid, but it will become valid later.
1471 /// See type level docs for details.
1472 #[inline]
1473 pub fn queue_register_component<T: Component>(&self) -> ComponentId {
1474 self.component_id::<T>().unwrap_or_else(|| {
1475 // SAFETY: We just checked that this type was not in the queue.
1476 unsafe {
1477 self.force_register_arbitrary_component(
1478 TypeId::of::<T>(),
1479 ComponentDescriptor::new::<T>(),
1480 |registrator, id, _descriptor| {
1481 // 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.
1482 #[expect(unused_unsafe, reason = "More precise to specify.")]
1483 unsafe {
1484 registrator.register_component_unchecked::<T>(&mut Vec::new(), id);
1485 }
1486 },
1487 )
1488 }
1489 })
1490 }
1491
1492 /// This is a queued version of [`ComponentsRegistrator::register_component_with_descriptor`].
1493 /// This will reserve an id and queue the registration.
1494 /// These registrations will be carried out at the next opportunity.
1495 ///
1496 /// # Note
1497 ///
1498 /// Technically speaking, the returned [`ComponentId`] is not valid, but it will become valid later.
1499 /// See type level docs for details.
1500 #[inline]
1501 pub fn queue_register_component_with_descriptor(
1502 &self,
1503 descriptor: ComponentDescriptor,
1504 ) -> ComponentId {
1505 self.force_register_arbitrary_dynamic(descriptor, |registrator, id, descriptor| {
1506 // SAFETY: Id uniqueness handled by caller.
1507 unsafe {
1508 registrator.register_component_inner(id, descriptor);
1509 }
1510 })
1511 }
1512
1513 /// This is a queued version of [`ComponentsRegistrator::register_resource`].
1514 /// This will reserve an id and queue the registration.
1515 /// These registrations will be carried out at the next opportunity.
1516 ///
1517 /// If this has already been registered or queued, this returns the previous [`ComponentId`].
1518 ///
1519 /// # Note
1520 ///
1521 /// Technically speaking, the returned [`ComponentId`] is not valid, but it will become valid later.
1522 /// See type level docs for details.
1523 #[inline]
1524 pub fn queue_register_resource<T: Resource>(&self) -> ComponentId {
1525 let type_id = TypeId::of::<T>();
1526 self.get_resource_id(type_id).unwrap_or_else(|| {
1527 // SAFETY: We just checked that this type was not in the queue.
1528 unsafe {
1529 self.force_register_arbitrary_resource(
1530 type_id,
1531 ComponentDescriptor::new_resource::<T>(),
1532 move |registrator, id, descriptor| {
1533 // 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.
1534 // SAFETY: Id uniqueness handled by caller, and the type_id matches descriptor.
1535 #[expect(unused_unsafe, reason = "More precise to specify.")]
1536 unsafe {
1537 registrator.register_resource_unchecked(type_id, id, descriptor);
1538 }
1539 },
1540 )
1541 }
1542 })
1543 }
1544
1545 /// This is a queued version of [`ComponentsRegistrator::register_non_send`].
1546 /// This will reserve an id and queue the registration.
1547 /// These registrations will be carried out at the next opportunity.
1548 ///
1549 /// If this has already been registered or queued, this returns the previous [`ComponentId`].
1550 ///
1551 /// # Note
1552 ///
1553 /// Technically speaking, the returned [`ComponentId`] is not valid, but it will become valid later.
1554 /// See type level docs for details.
1555 #[inline]
1556 pub fn queue_register_non_send<T: Any>(&self) -> ComponentId {
1557 let type_id = TypeId::of::<T>();
1558 self.get_resource_id(type_id).unwrap_or_else(|| {
1559 // SAFETY: We just checked that this type was not in the queue.
1560 unsafe {
1561 self.force_register_arbitrary_resource(
1562 type_id,
1563 ComponentDescriptor::new_non_send::<T>(StorageType::default()),
1564 move |registrator, id, descriptor| {
1565 // 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.
1566 // SAFETY: Id uniqueness handled by caller, and the type_id matches descriptor.
1567 #[expect(unused_unsafe, reason = "More precise to specify.")]
1568 unsafe {
1569 registrator.register_resource_unchecked(type_id, id, descriptor);
1570 }
1571 },
1572 )
1573 }
1574 })
1575 }
1576
1577 /// This is a queued version of [`ComponentsRegistrator::register_resource_with_descriptor`].
1578 /// This will reserve an id and queue the registration.
1579 /// These registrations will be carried out at the next opportunity.
1580 ///
1581 /// # Note
1582 ///
1583 /// Technically speaking, the returned [`ComponentId`] is not valid, but it will become valid later.
1584 /// See type level docs for details.
1585 #[inline]
1586 pub fn queue_register_resource_with_descriptor(
1587 &self,
1588 descriptor: ComponentDescriptor,
1589 ) -> ComponentId {
1590 self.force_register_arbitrary_dynamic(descriptor, |registrator, id, descriptor| {
1591 // SAFETY: Id uniqueness handled by caller.
1592 unsafe {
1593 registrator.register_component_inner(id, descriptor);
1594 }
1595 })
1596 }
1597}
1598
1599/// A [`Components`] wrapper that enables additional features, like registration.
1600pub struct ComponentsRegistrator<'w> {
1601 components: &'w mut Components,
1602 ids: &'w mut ComponentIds,
1603}
1604
1605impl Deref for ComponentsRegistrator<'_> {
1606 type Target = Components;
1607
1608 fn deref(&self) -> &Self::Target {
1609 self.components
1610 }
1611}
1612
1613impl DerefMut for ComponentsRegistrator<'_> {
1614 fn deref_mut(&mut self) -> &mut Self::Target {
1615 self.components
1616 }
1617}
1618
1619impl<'w> ComponentsRegistrator<'w> {
1620 /// Constructs a new [`ComponentsRegistrator`].
1621 ///
1622 /// # Safety
1623 ///
1624 /// The [`Components`] and [`ComponentIds`] must match.
1625 /// For example, they must be from the same world.
1626 pub unsafe fn new(components: &'w mut Components, ids: &'w mut ComponentIds) -> Self {
1627 Self { components, ids }
1628 }
1629
1630 /// Converts this [`ComponentsRegistrator`] into a [`ComponentsQueuedRegistrator`].
1631 /// This is intended for use to pass this value to a function that requires [`ComponentsQueuedRegistrator`].
1632 /// It is generally not a good idea to queue a registration when you can instead register directly on this type.
1633 pub fn as_queued(&self) -> ComponentsQueuedRegistrator<'_> {
1634 // SAFETY: ensured by the caller that created self.
1635 unsafe { ComponentsQueuedRegistrator::new(self.components, self.ids) }
1636 }
1637
1638 /// Applies every queued registration.
1639 /// This ensures that every valid [`ComponentId`] is registered,
1640 /// enabling retrieving [`ComponentInfo`], etc.
1641 pub fn apply_queued_registrations(&mut self) {
1642 if !self.any_queued_mut() {
1643 return;
1644 }
1645
1646 // Note:
1647 //
1648 // This is not just draining the queue. We need to empty the queue without removing the information from `Components`.
1649 // If we drained directly, we could break invariance.
1650 //
1651 // For example, say `ComponentA` and `ComponentB` are queued, and `ComponentA` requires `ComponentB`.
1652 // If we drain directly, and `ComponentA` was the first to be registered, then, when `ComponentA`
1653 // registers `ComponentB` in `Component::register_required_components`,
1654 // `Components` will not know that `ComponentB` was queued
1655 // (since it will have been drained from the queue.)
1656 // If that happened, `Components` would assign a new `ComponentId` to `ComponentB`
1657 // which would be *different* than the id it was assigned in the queue.
1658 // Then, when the drain iterator gets to `ComponentB`,
1659 // it would be unsafely registering `ComponentB`, which is already registered.
1660 //
1661 // As a result, we need to pop from each queue one by one instead of draining.
1662
1663 // components
1664 while let Some(registrator) = {
1665 let queued = self
1666 .components
1667 .queued
1668 .get_mut()
1669 .unwrap_or_else(PoisonError::into_inner);
1670 queued.components.keys().next().copied().map(|type_id| {
1671 // SAFETY: the id just came from a valid iterator.
1672 unsafe { queued.components.remove(&type_id).debug_checked_unwrap() }
1673 })
1674 } {
1675 registrator.register(self);
1676 }
1677
1678 // resources
1679 while let Some(registrator) = {
1680 let queued = self
1681 .components
1682 .queued
1683 .get_mut()
1684 .unwrap_or_else(PoisonError::into_inner);
1685 queued.resources.keys().next().copied().map(|type_id| {
1686 // SAFETY: the id just came from a valid iterator.
1687 unsafe { queued.resources.remove(&type_id).debug_checked_unwrap() }
1688 })
1689 } {
1690 registrator.register(self);
1691 }
1692
1693 // dynamic
1694 let queued = &mut self
1695 .components
1696 .queued
1697 .get_mut()
1698 .unwrap_or_else(PoisonError::into_inner);
1699 if !queued.dynamic_registrations.is_empty() {
1700 for registrator in core::mem::take(&mut queued.dynamic_registrations) {
1701 registrator.register(self);
1702 }
1703 }
1704 }
1705
1706 /// Registers a [`Component`] of type `T` with this instance.
1707 /// If a component of this type has already been registered, this will return
1708 /// the ID of the pre-existing component.
1709 ///
1710 /// # See also
1711 ///
1712 /// * [`Components::component_id()`]
1713 /// * [`ComponentsRegistrator::register_component_with_descriptor()`]
1714 #[inline]
1715 pub fn register_component<T: Component>(&mut self) -> ComponentId {
1716 self.register_component_checked::<T>(&mut Vec::new())
1717 }
1718
1719 /// Same as [`Self::register_component_unchecked`] but keeps a checks for safety.
1720 #[inline]
1721 fn register_component_checked<T: Component>(
1722 &mut self,
1723 recursion_check_stack: &mut Vec<ComponentId>,
1724 ) -> ComponentId {
1725 let type_id = TypeId::of::<T>();
1726 if let Some(id) = self.indices.get(&type_id) {
1727 return *id;
1728 }
1729
1730 if let Some(registrator) = self
1731 .components
1732 .queued
1733 .get_mut()
1734 .unwrap_or_else(PoisonError::into_inner)
1735 .components
1736 .remove(&type_id)
1737 {
1738 // If we are trying to register something that has already been queued, we respect the queue.
1739 // Just like if we are trying to register something that already is, we respect the first registration.
1740 return registrator.register(self);
1741 }
1742
1743 let id = self.ids.next_mut();
1744 // SAFETY: The component is not currently registered, and the id is fresh.
1745 unsafe {
1746 self.register_component_unchecked::<T>(recursion_check_stack, id);
1747 }
1748 id
1749 }
1750
1751 /// # Safety
1752 ///
1753 /// Neither this component, nor its id may be registered or queued. This must be a new registration.
1754 #[inline]
1755 unsafe fn register_component_unchecked<T: Component>(
1756 &mut self,
1757 recursion_check_stack: &mut Vec<ComponentId>,
1758 id: ComponentId,
1759 ) {
1760 // SAFETY: ensured by caller.
1761 unsafe {
1762 self.register_component_inner(id, ComponentDescriptor::new::<T>());
1763 }
1764 let type_id = TypeId::of::<T>();
1765 let prev = self.indices.insert(type_id, id);
1766 debug_assert!(prev.is_none());
1767
1768 let mut required_components = RequiredComponents::default();
1769 T::register_required_components(
1770 id,
1771 self,
1772 &mut required_components,
1773 0,
1774 recursion_check_stack,
1775 );
1776 // SAFETY: we just inserted it in `register_component_inner`
1777 let info = unsafe {
1778 &mut self
1779 .components
1780 .components
1781 .get_mut(id.0)
1782 .debug_checked_unwrap()
1783 .as_mut()
1784 .debug_checked_unwrap()
1785 };
1786
1787 #[expect(
1788 deprecated,
1789 reason = "need to use this method until it is removed to ensure user defined components register hooks correctly"
1790 )]
1791 // TODO: Replace with `info.hooks.update_from_component::<T>();` once `Component::register_component_hooks` is removed
1792 T::register_component_hooks(&mut info.hooks);
1793
1794 info.required_components = required_components;
1795 }
1796
1797 /// Registers a component described by `descriptor`.
1798 ///
1799 /// # Note
1800 ///
1801 /// If this method is called multiple times with identical descriptors, a distinct [`ComponentId`]
1802 /// will be created for each one.
1803 ///
1804 /// # See also
1805 ///
1806 /// * [`Components::component_id()`]
1807 /// * [`ComponentsRegistrator::register_component()`]
1808 #[inline]
1809 pub fn register_component_with_descriptor(
1810 &mut self,
1811 descriptor: ComponentDescriptor,
1812 ) -> ComponentId {
1813 let id = self.ids.next_mut();
1814 // SAFETY: The id is fresh.
1815 unsafe {
1816 self.register_component_inner(id, descriptor);
1817 }
1818 id
1819 }
1820
1821 // NOTE: This should maybe be private, but it is currently public so that `bevy_ecs_macros` can use it.
1822 // We can't directly move this there either, because this uses `Components::get_required_by_mut`,
1823 // which is private, and could be equally risky to expose to users.
1824 /// Registers the given component `R` and [required components] inherited from it as required by `T`,
1825 /// and adds `T` to their lists of requirees.
1826 ///
1827 /// The given `inheritance_depth` determines how many levels of inheritance deep the requirement is.
1828 /// A direct requirement has a depth of `0`, and each level of inheritance increases the depth by `1`.
1829 /// Lower depths are more specific requirements, and can override existing less specific registrations.
1830 ///
1831 /// The `recursion_check_stack` allows checking whether this component tried to register itself as its
1832 /// own (indirect) required component.
1833 ///
1834 /// This method does *not* register any components as required by components that require `T`.
1835 ///
1836 /// Only use this method if you know what you are doing. In most cases, you should instead use [`World::register_required_components`],
1837 /// or the equivalent method in `bevy_app::App`.
1838 ///
1839 /// [required component]: Component#required-components
1840 #[doc(hidden)]
1841 pub fn register_required_components_manual<T: Component, R: Component>(
1842 &mut self,
1843 required_components: &mut RequiredComponents,
1844 constructor: fn() -> R,
1845 inheritance_depth: u16,
1846 recursion_check_stack: &mut Vec<ComponentId>,
1847 ) {
1848 let requiree = self.register_component_checked::<T>(recursion_check_stack);
1849 let required = self.register_component_checked::<R>(recursion_check_stack);
1850
1851 // SAFETY: We just created the components.
1852 unsafe {
1853 self.register_required_components_manual_unchecked::<R>(
1854 requiree,
1855 required,
1856 required_components,
1857 constructor,
1858 inheritance_depth,
1859 );
1860 }
1861 }
1862
1863 /// Registers a [`Resource`] of type `T` with this instance.
1864 /// If a resource of this type has already been registered, this will return
1865 /// the ID of the pre-existing resource.
1866 ///
1867 /// # See also
1868 ///
1869 /// * [`Components::resource_id()`]
1870 /// * [`ComponentsRegistrator::register_resource_with_descriptor()`]
1871 #[inline]
1872 pub fn register_resource<T: Resource>(&mut self) -> ComponentId {
1873 // SAFETY: The [`ComponentDescriptor`] matches the [`TypeId`]
1874 unsafe {
1875 self.register_resource_with(TypeId::of::<T>(), || {
1876 ComponentDescriptor::new_resource::<T>()
1877 })
1878 }
1879 }
1880
1881 /// Registers a [non-send resource](crate::system::NonSend) of type `T` with this instance.
1882 /// If a resource of this type has already been registered, this will return
1883 /// the ID of the pre-existing resource.
1884 #[inline]
1885 pub fn register_non_send<T: Any>(&mut self) -> ComponentId {
1886 // SAFETY: The [`ComponentDescriptor`] matches the [`TypeId`]
1887 unsafe {
1888 self.register_resource_with(TypeId::of::<T>(), || {
1889 ComponentDescriptor::new_non_send::<T>(StorageType::default())
1890 })
1891 }
1892 }
1893
1894 /// Same as [`Components::register_resource_unchecked`] but handles safety.
1895 ///
1896 /// # Safety
1897 ///
1898 /// The [`ComponentDescriptor`] must match the [`TypeId`].
1899 #[inline]
1900 unsafe fn register_resource_with(
1901 &mut self,
1902 type_id: TypeId,
1903 descriptor: impl FnOnce() -> ComponentDescriptor,
1904 ) -> ComponentId {
1905 if let Some(id) = self.resource_indices.get(&type_id) {
1906 return *id;
1907 }
1908
1909 if let Some(registrator) = self
1910 .components
1911 .queued
1912 .get_mut()
1913 .unwrap_or_else(PoisonError::into_inner)
1914 .resources
1915 .remove(&type_id)
1916 {
1917 // If we are trying to register something that has already been queued, we respect the queue.
1918 // Just like if we are trying to register something that already is, we respect the first registration.
1919 return registrator.register(self);
1920 }
1921
1922 let id = self.ids.next_mut();
1923 // SAFETY: The resource is not currently registered, the id is fresh, and the [`ComponentDescriptor`] matches the [`TypeId`]
1924 unsafe {
1925 self.register_resource_unchecked(type_id, id, descriptor());
1926 }
1927 id
1928 }
1929
1930 /// Registers a [`Resource`] described by `descriptor`.
1931 ///
1932 /// # Note
1933 ///
1934 /// If this method is called multiple times with identical descriptors, a distinct [`ComponentId`]
1935 /// will be created for each one.
1936 ///
1937 /// # See also
1938 ///
1939 /// * [`Components::resource_id()`]
1940 /// * [`ComponentsRegistrator::register_resource()`]
1941 #[inline]
1942 pub fn register_resource_with_descriptor(
1943 &mut self,
1944 descriptor: ComponentDescriptor,
1945 ) -> ComponentId {
1946 let id = self.ids.next_mut();
1947 // SAFETY: The id is fresh.
1948 unsafe {
1949 self.register_component_inner(id, descriptor);
1950 }
1951 id
1952 }
1953}
1954
1955/// Stores metadata associated with each kind of [`Component`] in a given [`World`].
1956#[derive(Debug, Default)]
1957pub struct Components {
1958 components: Vec<Option<ComponentInfo>>,
1959 indices: TypeIdMap<ComponentId>,
1960 resource_indices: TypeIdMap<ComponentId>,
1961 // This is kept internal and local to verify that no deadlocks can occor.
1962 queued: bevy_platform::sync::RwLock<QueuedComponents>,
1963}
1964
1965impl Components {
1966 /// This registers any descriptor, component or resource.
1967 ///
1968 /// # Safety
1969 ///
1970 /// The id must have never been registered before. This must be a fresh registration.
1971 #[inline]
1972 unsafe fn register_component_inner(
1973 &mut self,
1974 id: ComponentId,
1975 descriptor: ComponentDescriptor,
1976 ) {
1977 let info = ComponentInfo::new(id, descriptor);
1978 let least_len = id.0 + 1;
1979 if self.components.len() < least_len {
1980 self.components.resize_with(least_len, || None);
1981 }
1982 // SAFETY: We just extended the vec to make this index valid.
1983 let slot = unsafe { self.components.get_mut(id.0).debug_checked_unwrap() };
1984 // Caller ensures id is unique
1985 debug_assert!(slot.is_none());
1986 *slot = Some(info);
1987 }
1988
1989 /// Returns the number of components registered or queued with this instance.
1990 #[inline]
1991 pub fn len(&self) -> usize {
1992 self.num_queued() + self.num_registered()
1993 }
1994
1995 /// Returns `true` if there are no components registered or queued with this instance. Otherwise, this returns `false`.
1996 #[inline]
1997 pub fn is_empty(&self) -> bool {
1998 self.len() == 0
1999 }
2000
2001 /// Returns the number of components registered with this instance.
2002 #[inline]
2003 pub fn num_queued(&self) -> usize {
2004 let queued = self.queued.read().unwrap_or_else(PoisonError::into_inner);
2005 queued.components.len() + queued.dynamic_registrations.len() + queued.resources.len()
2006 }
2007
2008 /// Returns `true` if there are any components registered with this instance. Otherwise, this returns `false`.
2009 #[inline]
2010 pub fn any_queued(&self) -> bool {
2011 self.num_queued() > 0
2012 }
2013
2014 /// A faster version of [`Self::num_queued`].
2015 #[inline]
2016 pub fn num_queued_mut(&mut self) -> usize {
2017 let queued = self
2018 .queued
2019 .get_mut()
2020 .unwrap_or_else(PoisonError::into_inner);
2021 queued.components.len() + queued.dynamic_registrations.len() + queued.resources.len()
2022 }
2023
2024 /// A faster version of [`Self::any_queued`].
2025 #[inline]
2026 pub fn any_queued_mut(&mut self) -> bool {
2027 self.num_queued_mut() > 0
2028 }
2029
2030 /// Returns the number of components registered with this instance.
2031 #[inline]
2032 pub fn num_registered(&self) -> usize {
2033 self.components.len()
2034 }
2035
2036 /// Returns `true` if there are any components registered with this instance. Otherwise, this returns `false`.
2037 #[inline]
2038 pub fn any_registered(&self) -> bool {
2039 self.num_registered() > 0
2040 }
2041
2042 /// Gets the metadata associated with the given component, if it is registered.
2043 /// This will return `None` if the id is not regiserted or is queued.
2044 ///
2045 /// 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.
2046 #[inline]
2047 pub fn get_info(&self, id: ComponentId) -> Option<&ComponentInfo> {
2048 self.components.get(id.0).and_then(|info| info.as_ref())
2049 }
2050
2051 /// Gets the [`ComponentDescriptor`] of the component with this [`ComponentId`] if it is present.
2052 /// This will return `None` only if the id is neither regisered nor queued to be registered.
2053 ///
2054 /// Currently, the [`Cow`] will be [`Cow::Owned`] if and only if the component is queued. It will be [`Cow::Borrowed`] otherwise.
2055 ///
2056 /// 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.
2057 #[inline]
2058 pub fn get_descriptor<'a>(&'a self, id: ComponentId) -> Option<Cow<'a, ComponentDescriptor>> {
2059 self.components
2060 .get(id.0)
2061 .and_then(|info| info.as_ref().map(|info| Cow::Borrowed(&info.descriptor)))
2062 .or_else(|| {
2063 let queued = self.queued.read().unwrap_or_else(PoisonError::into_inner);
2064 // first check components, then resources, then dynamic
2065 queued
2066 .components
2067 .values()
2068 .chain(queued.resources.values())
2069 .chain(queued.dynamic_registrations.iter())
2070 .find(|queued| queued.id == id)
2071 .map(|queued| Cow::Owned(queued.descriptor.clone()))
2072 })
2073 }
2074
2075 /// Gets the name of the component with this [`ComponentId`] if it is present.
2076 /// This will return `None` only if the id is neither regisered nor queued to be registered.
2077 ///
2078 /// 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.
2079 #[inline]
2080 pub fn get_name<'a>(&'a self, id: ComponentId) -> Option<Cow<'a, str>> {
2081 self.components
2082 .get(id.0)
2083 .and_then(|info| {
2084 info.as_ref()
2085 .map(|info| Cow::Borrowed(info.descriptor.name()))
2086 })
2087 .or_else(|| {
2088 let queued = self.queued.read().unwrap_or_else(PoisonError::into_inner);
2089 // first check components, then resources, then dynamic
2090 queued
2091 .components
2092 .values()
2093 .chain(queued.resources.values())
2094 .chain(queued.dynamic_registrations.iter())
2095 .find(|queued| queued.id == id)
2096 .map(|queued| queued.descriptor.name.clone())
2097 })
2098 }
2099
2100 /// Gets the metadata associated with the given component.
2101 /// # Safety
2102 ///
2103 /// `id` must be a valid and fully registered [`ComponentId`].
2104 #[inline]
2105 pub unsafe fn get_info_unchecked(&self, id: ComponentId) -> &ComponentInfo {
2106 // SAFETY: The caller ensures `id` is valid.
2107 unsafe {
2108 self.components
2109 .get(id.0)
2110 .debug_checked_unwrap()
2111 .as_ref()
2112 .debug_checked_unwrap()
2113 }
2114 }
2115
2116 #[inline]
2117 pub(crate) fn get_hooks_mut(&mut self, id: ComponentId) -> Option<&mut ComponentHooks> {
2118 self.components
2119 .get_mut(id.0)
2120 .and_then(|info| info.as_mut().map(|info| &mut info.hooks))
2121 }
2122
2123 #[inline]
2124 pub(crate) fn get_required_components_mut(
2125 &mut self,
2126 id: ComponentId,
2127 ) -> Option<&mut RequiredComponents> {
2128 self.components
2129 .get_mut(id.0)
2130 .and_then(|info| info.as_mut().map(|info| &mut info.required_components))
2131 }
2132
2133 /// Registers the given component `R` and [required components] inherited from it as required by `T`.
2134 ///
2135 /// When `T` is added to an entity, `R` will also be added if it was not already provided.
2136 /// The given `constructor` will be used for the creation of `R`.
2137 ///
2138 /// [required components]: Component#required-components
2139 ///
2140 /// # Safety
2141 ///
2142 /// The given component IDs `required` and `requiree` must be valid.
2143 ///
2144 /// # Errors
2145 ///
2146 /// Returns a [`RequiredComponentsError`] if the `required` component is already a directly required component for the `requiree`.
2147 ///
2148 /// Indirect requirements through other components are allowed. In those cases, the more specific
2149 /// registration will be used.
2150 pub(crate) unsafe fn register_required_components<R: Component>(
2151 &mut self,
2152 requiree: ComponentId,
2153 required: ComponentId,
2154 constructor: fn() -> R,
2155 ) -> Result<(), RequiredComponentsError> {
2156 // SAFETY: The caller ensures that the `requiree` is valid.
2157 let required_components = unsafe {
2158 self.get_required_components_mut(requiree)
2159 .debug_checked_unwrap()
2160 };
2161
2162 // Cannot directly require the same component twice.
2163 if required_components
2164 .0
2165 .get(&required)
2166 .is_some_and(|c| c.inheritance_depth == 0)
2167 {
2168 return Err(RequiredComponentsError::DuplicateRegistration(
2169 requiree, required,
2170 ));
2171 }
2172
2173 // Register the required component for the requiree.
2174 // This is a direct requirement with a depth of `0`.
2175 required_components.register_by_id(required, constructor, 0);
2176
2177 // Add the requiree to the list of components that require the required component.
2178 // SAFETY: The component is in the list of required components, so it must exist already.
2179 let required_by = unsafe { self.get_required_by_mut(required).debug_checked_unwrap() };
2180 required_by.insert(requiree);
2181
2182 let mut required_components_tmp = RequiredComponents::default();
2183 // SAFETY: The caller ensures that the `requiree` and `required` components are valid.
2184 let inherited_requirements = unsafe {
2185 self.register_inherited_required_components(
2186 requiree,
2187 required,
2188 &mut required_components_tmp,
2189 )
2190 };
2191
2192 // SAFETY: The caller ensures that the `requiree` is valid.
2193 let required_components = unsafe {
2194 self.get_required_components_mut(requiree)
2195 .debug_checked_unwrap()
2196 };
2197 required_components.0.extend(required_components_tmp.0);
2198
2199 // Propagate the new required components up the chain to all components that require the requiree.
2200 if let Some(required_by) = self
2201 .get_required_by(requiree)
2202 .map(|set| set.iter().copied().collect::<SmallVec<[ComponentId; 8]>>())
2203 {
2204 // `required` is now required by anything that `requiree` was required by.
2205 self.get_required_by_mut(required)
2206 .unwrap()
2207 .extend(required_by.iter().copied());
2208 for &required_by_id in required_by.iter() {
2209 // SAFETY: The component is in the list of required components, so it must exist already.
2210 let required_components = unsafe {
2211 self.get_required_components_mut(required_by_id)
2212 .debug_checked_unwrap()
2213 };
2214
2215 // Register the original required component in the "parent" of the requiree.
2216 // The inheritance depth is 1 deeper than the `requiree` wrt `required_by_id`.
2217 let depth = required_components.0.get(&requiree).expect("requiree is required by required_by_id, so its required_components must include requiree").inheritance_depth;
2218 required_components.register_by_id(required, constructor, depth + 1);
2219
2220 for (component_id, component) in inherited_requirements.iter() {
2221 // Register the required component.
2222 // The inheritance depth of inherited components is whatever the requiree's
2223 // depth is relative to `required_by_id`, plus the inheritance depth of the
2224 // inherited component relative to the requiree, plus 1 to account for the
2225 // requiree in between.
2226 // SAFETY: Component ID and constructor match the ones on the original requiree.
2227 // The original requiree is responsible for making sure the registration is safe.
2228 unsafe {
2229 required_components.register_dynamic_with(
2230 *component_id,
2231 component.inheritance_depth + depth + 1,
2232 || component.constructor.clone(),
2233 );
2234 };
2235 }
2236 }
2237 }
2238
2239 Ok(())
2240 }
2241
2242 /// Registers the components inherited from `required` for the given `requiree`,
2243 /// returning the requirements in a list.
2244 ///
2245 /// # Safety
2246 ///
2247 /// The given component IDs `requiree` and `required` must be valid.
2248 unsafe fn register_inherited_required_components(
2249 &mut self,
2250 requiree: ComponentId,
2251 required: ComponentId,
2252 required_components: &mut RequiredComponents,
2253 ) -> Vec<(ComponentId, RequiredComponent)> {
2254 // Get required components inherited from the `required` component.
2255 // SAFETY: The caller ensures that the `required` component is valid.
2256 let required_component_info = unsafe { self.get_info(required).debug_checked_unwrap() };
2257 let inherited_requirements: Vec<(ComponentId, RequiredComponent)> = required_component_info
2258 .required_components()
2259 .0
2260 .iter()
2261 .map(|(component_id, required_component)| {
2262 (
2263 *component_id,
2264 RequiredComponent {
2265 constructor: required_component.constructor.clone(),
2266 // Add `1` to the inheritance depth since this will be registered
2267 // for the component that requires `required`.
2268 inheritance_depth: required_component.inheritance_depth + 1,
2269 },
2270 )
2271 })
2272 .collect();
2273
2274 // Register the new required components.
2275 for (component_id, component) in inherited_requirements.iter() {
2276 // Register the required component for the requiree.
2277 // SAFETY: Component ID and constructor match the ones on the original requiree.
2278 unsafe {
2279 required_components.register_dynamic_with(
2280 *component_id,
2281 component.inheritance_depth,
2282 || component.constructor.clone(),
2283 );
2284 };
2285
2286 // Add the requiree to the list of components that require the required component.
2287 // SAFETY: The caller ensures that the required components are valid.
2288 let required_by = unsafe {
2289 self.get_required_by_mut(*component_id)
2290 .debug_checked_unwrap()
2291 };
2292 required_by.insert(requiree);
2293 }
2294
2295 inherited_requirements
2296 }
2297
2298 /// Registers the given component `R` and [required components] inherited from it as required by `T`,
2299 /// and adds `T` to their lists of requirees.
2300 ///
2301 /// The given `inheritance_depth` determines how many levels of inheritance deep the requirement is.
2302 /// A direct requirement has a depth of `0`, and each level of inheritance increases the depth by `1`.
2303 /// Lower depths are more specific requirements, and can override existing less specific registrations.
2304 ///
2305 /// This method does *not* register any components as required by components that require `T`.
2306 ///
2307 /// [required component]: Component#required-components
2308 ///
2309 /// # Safety
2310 ///
2311 /// The given component IDs `required` and `requiree` must be valid.
2312 pub(crate) unsafe fn register_required_components_manual_unchecked<R: Component>(
2313 &mut self,
2314 requiree: ComponentId,
2315 required: ComponentId,
2316 required_components: &mut RequiredComponents,
2317 constructor: fn() -> R,
2318 inheritance_depth: u16,
2319 ) {
2320 // Components cannot require themselves.
2321 if required == requiree {
2322 return;
2323 }
2324
2325 // Register the required component `R` for the requiree.
2326 required_components.register_by_id(required, constructor, inheritance_depth);
2327
2328 // Add the requiree to the list of components that require `R`.
2329 // SAFETY: The caller ensures that the component ID is valid.
2330 // Assuming it is valid, the component is in the list of required components, so it must exist already.
2331 let required_by = unsafe { self.get_required_by_mut(required).debug_checked_unwrap() };
2332 required_by.insert(requiree);
2333
2334 self.register_inherited_required_components(requiree, required, required_components);
2335 }
2336
2337 #[inline]
2338 pub(crate) fn get_required_by(&self, id: ComponentId) -> Option<&HashSet<ComponentId>> {
2339 self.components
2340 .get(id.0)
2341 .and_then(|info| info.as_ref().map(|info| &info.required_by))
2342 }
2343
2344 #[inline]
2345 pub(crate) fn get_required_by_mut(
2346 &mut self,
2347 id: ComponentId,
2348 ) -> Option<&mut HashSet<ComponentId>> {
2349 self.components
2350 .get_mut(id.0)
2351 .and_then(|info| info.as_mut().map(|info| &mut info.required_by))
2352 }
2353
2354 /// Returns true if the [`ComponentId`] is fully registered and valid.
2355 /// Ids may be invalid if they are still queued to be registered.
2356 /// Those ids are still correct, but they are not usable in every context yet.
2357 #[inline]
2358 pub fn is_id_valid(&self, id: ComponentId) -> bool {
2359 self.components.get(id.0).is_some_and(Option::is_some)
2360 }
2361
2362 /// Type-erased equivalent of [`Components::valid_component_id()`].
2363 #[inline]
2364 pub fn get_valid_id(&self, type_id: TypeId) -> Option<ComponentId> {
2365 self.indices.get(&type_id).copied()
2366 }
2367
2368 /// Returns the [`ComponentId`] of the given [`Component`] type `T` if it is fully registered.
2369 /// If you want to include queued registration, see [`Components::component_id()`].
2370 ///
2371 /// ```
2372 /// use bevy_ecs::prelude::*;
2373 ///
2374 /// let mut world = World::new();
2375 ///
2376 /// #[derive(Component)]
2377 /// struct ComponentA;
2378 ///
2379 /// let component_a_id = world.register_component::<ComponentA>();
2380 ///
2381 /// assert_eq!(component_a_id, world.components().valid_component_id::<ComponentA>().unwrap())
2382 /// ```
2383 ///
2384 /// # See also
2385 ///
2386 /// * [`Components::get_valid_id()`]
2387 /// * [`Components::valid_resource_id()`]
2388 /// * [`World::component_id()`]
2389 #[inline]
2390 pub fn valid_component_id<T: Component>(&self) -> Option<ComponentId> {
2391 self.get_id(TypeId::of::<T>())
2392 }
2393
2394 /// Type-erased equivalent of [`Components::valid_resource_id()`].
2395 #[inline]
2396 pub fn get_valid_resource_id(&self, type_id: TypeId) -> Option<ComponentId> {
2397 self.resource_indices.get(&type_id).copied()
2398 }
2399
2400 /// Returns the [`ComponentId`] of the given [`Resource`] type `T` if it is fully registered.
2401 /// If you want to include queued registration, see [`Components::resource_id()`].
2402 ///
2403 /// ```
2404 /// use bevy_ecs::prelude::*;
2405 ///
2406 /// let mut world = World::new();
2407 ///
2408 /// #[derive(Resource, Default)]
2409 /// struct ResourceA;
2410 ///
2411 /// let resource_a_id = world.init_resource::<ResourceA>();
2412 ///
2413 /// assert_eq!(resource_a_id, world.components().valid_resource_id::<ResourceA>().unwrap())
2414 /// ```
2415 ///
2416 /// # See also
2417 ///
2418 /// * [`Components::valid_component_id()`]
2419 /// * [`Components::get_resource_id()`]
2420 #[inline]
2421 pub fn valid_resource_id<T: Resource>(&self) -> Option<ComponentId> {
2422 self.get_resource_id(TypeId::of::<T>())
2423 }
2424
2425 /// Type-erased equivalent of [`Components::component_id()`].
2426 #[inline]
2427 pub fn get_id(&self, type_id: TypeId) -> Option<ComponentId> {
2428 self.indices.get(&type_id).copied().or_else(|| {
2429 self.queued
2430 .read()
2431 .unwrap_or_else(PoisonError::into_inner)
2432 .components
2433 .get(&type_id)
2434 .map(|queued| queued.id)
2435 })
2436 }
2437
2438 /// Returns the [`ComponentId`] of the given [`Component`] type `T`.
2439 ///
2440 /// The returned `ComponentId` is specific to the `Components` instance
2441 /// it was retrieved from and should not be used with another `Components`
2442 /// instance.
2443 ///
2444 /// Returns [`None`] if the `Component` type has not
2445 /// yet been initialized using [`ComponentsRegistrator::register_component()`] or [`ComponentsQueuedRegistrator::queue_register_component()`].
2446 ///
2447 /// ```
2448 /// use bevy_ecs::prelude::*;
2449 ///
2450 /// let mut world = World::new();
2451 ///
2452 /// #[derive(Component)]
2453 /// struct ComponentA;
2454 ///
2455 /// let component_a_id = world.register_component::<ComponentA>();
2456 ///
2457 /// assert_eq!(component_a_id, world.components().component_id::<ComponentA>().unwrap())
2458 /// ```
2459 ///
2460 /// # See also
2461 ///
2462 /// * [`Components::get_id()`]
2463 /// * [`Components::resource_id()`]
2464 /// * [`World::component_id()`]
2465 #[inline]
2466 pub fn component_id<T: Component>(&self) -> Option<ComponentId> {
2467 self.get_id(TypeId::of::<T>())
2468 }
2469
2470 /// Type-erased equivalent of [`Components::resource_id()`].
2471 #[inline]
2472 pub fn get_resource_id(&self, type_id: TypeId) -> Option<ComponentId> {
2473 self.resource_indices.get(&type_id).copied().or_else(|| {
2474 self.queued
2475 .read()
2476 .unwrap_or_else(PoisonError::into_inner)
2477 .resources
2478 .get(&type_id)
2479 .map(|queued| queued.id)
2480 })
2481 }
2482
2483 /// Returns the [`ComponentId`] of the given [`Resource`] type `T`.
2484 ///
2485 /// The returned `ComponentId` is specific to the `Components` instance
2486 /// it was retrieved from and should not be used with another `Components`
2487 /// instance.
2488 ///
2489 /// Returns [`None`] if the `Resource` type has not
2490 /// yet been initialized using [`ComponentsRegistrator::register_resource()`] or [`ComponentsQueuedRegistrator::queue_register_resource()`].
2491 ///
2492 /// ```
2493 /// use bevy_ecs::prelude::*;
2494 ///
2495 /// let mut world = World::new();
2496 ///
2497 /// #[derive(Resource, Default)]
2498 /// struct ResourceA;
2499 ///
2500 /// let resource_a_id = world.init_resource::<ResourceA>();
2501 ///
2502 /// assert_eq!(resource_a_id, world.components().resource_id::<ResourceA>().unwrap())
2503 /// ```
2504 ///
2505 /// # See also
2506 ///
2507 /// * [`Components::component_id()`]
2508 /// * [`Components::get_resource_id()`]
2509 #[inline]
2510 pub fn resource_id<T: Resource>(&self) -> Option<ComponentId> {
2511 self.get_resource_id(TypeId::of::<T>())
2512 }
2513
2514 /// # Safety
2515 ///
2516 /// The [`ComponentDescriptor`] must match the [`TypeId`].
2517 /// The [`ComponentId`] must be unique.
2518 /// The [`TypeId`] and [`ComponentId`] must not be registered or queued.
2519 #[inline]
2520 unsafe fn register_resource_unchecked(
2521 &mut self,
2522 type_id: TypeId,
2523 component_id: ComponentId,
2524 descriptor: ComponentDescriptor,
2525 ) {
2526 // SAFETY: ensured by caller
2527 unsafe {
2528 self.register_component_inner(component_id, descriptor);
2529 }
2530 let prev = self.resource_indices.insert(type_id, component_id);
2531 debug_assert!(prev.is_none());
2532 }
2533
2534 /// Gets an iterator over all components fully registered with this instance.
2535 pub fn iter_registered(&self) -> impl Iterator<Item = &ComponentInfo> + '_ {
2536 self.components.iter().filter_map(Option::as_ref)
2537 }
2538}
2539
2540/// A value that tracks when a system ran relative to other systems.
2541/// This is used to power change detection.
2542///
2543/// *Note* that a system that hasn't been run yet has a `Tick` of 0.
2544#[derive(Copy, Clone, Default, Debug, Eq, Hash, PartialEq)]
2545#[cfg_attr(
2546 feature = "bevy_reflect",
2547 derive(Reflect),
2548 reflect(Debug, Hash, PartialEq, Clone)
2549)]
2550pub struct Tick {
2551 tick: u32,
2552}
2553
2554impl Tick {
2555 /// The maximum relative age for a change tick.
2556 /// The value of this is equal to [`MAX_CHANGE_AGE`].
2557 ///
2558 /// Since change detection will not work for any ticks older than this,
2559 /// ticks are periodically scanned to ensure their relative values are below this.
2560 pub const MAX: Self = Self::new(MAX_CHANGE_AGE);
2561
2562 /// Creates a new [`Tick`] wrapping the given value.
2563 #[inline]
2564 pub const fn new(tick: u32) -> Self {
2565 Self { tick }
2566 }
2567
2568 /// Gets the value of this change tick.
2569 #[inline]
2570 pub const fn get(self) -> u32 {
2571 self.tick
2572 }
2573
2574 /// Sets the value of this change tick.
2575 #[inline]
2576 pub fn set(&mut self, tick: u32) {
2577 self.tick = tick;
2578 }
2579
2580 /// Returns `true` if this `Tick` occurred since the system's `last_run`.
2581 ///
2582 /// `this_run` is the current tick of the system, used as a reference to help deal with wraparound.
2583 #[inline]
2584 pub fn is_newer_than(self, last_run: Tick, this_run: Tick) -> bool {
2585 // This works even with wraparound because the world tick (`this_run`) is always "newer" than
2586 // `last_run` and `self.tick`, and we scan periodically to clamp `ComponentTicks` values
2587 // so they never get older than `u32::MAX` (the difference would overflow).
2588 //
2589 // The clamp here ensures determinism (since scans could differ between app runs).
2590 let ticks_since_insert = this_run.relative_to(self).tick.min(MAX_CHANGE_AGE);
2591 let ticks_since_system = this_run.relative_to(last_run).tick.min(MAX_CHANGE_AGE);
2592
2593 ticks_since_system > ticks_since_insert
2594 }
2595
2596 /// Returns a change tick representing the relationship between `self` and `other`.
2597 #[inline]
2598 pub(crate) fn relative_to(self, other: Self) -> Self {
2599 let tick = self.tick.wrapping_sub(other.tick);
2600 Self { tick }
2601 }
2602
2603 /// Wraps this change tick's value if it exceeds [`Tick::MAX`].
2604 ///
2605 /// Returns `true` if wrapping was performed. Otherwise, returns `false`.
2606 #[inline]
2607 pub(crate) fn check_tick(&mut self, tick: Tick) -> bool {
2608 let age = tick.relative_to(*self);
2609 // This comparison assumes that `age` has not overflowed `u32::MAX` before, which will be true
2610 // so long as this check always runs before that can happen.
2611 if age.get() > Self::MAX.get() {
2612 *self = tick.relative_to(Self::MAX);
2613 true
2614 } else {
2615 false
2616 }
2617 }
2618}
2619
2620/// Interior-mutable access to the [`Tick`]s for a single component or resource.
2621#[derive(Copy, Clone, Debug)]
2622pub struct TickCells<'a> {
2623 /// The tick indicating when the value was added to the world.
2624 pub added: &'a UnsafeCell<Tick>,
2625 /// The tick indicating the last time the value was modified.
2626 pub changed: &'a UnsafeCell<Tick>,
2627}
2628
2629impl<'a> TickCells<'a> {
2630 /// # Safety
2631 /// All cells contained within must uphold the safety invariants of [`UnsafeCellDeref::read`].
2632 #[inline]
2633 pub(crate) unsafe fn read(&self) -> ComponentTicks {
2634 ComponentTicks {
2635 // SAFETY: The callers uphold the invariants for `read`.
2636 added: unsafe { self.added.read() },
2637 // SAFETY: The callers uphold the invariants for `read`.
2638 changed: unsafe { self.changed.read() },
2639 }
2640 }
2641}
2642
2643/// Records when a component or resource was added and when it was last mutably dereferenced (or added).
2644#[derive(Copy, Clone, Debug)]
2645#[cfg_attr(feature = "bevy_reflect", derive(Reflect), reflect(Debug, Clone))]
2646pub struct ComponentTicks {
2647 /// Tick recording the time this component or resource was added.
2648 pub added: Tick,
2649
2650 /// Tick recording the time this component or resource was most recently changed.
2651 pub changed: Tick,
2652}
2653
2654impl ComponentTicks {
2655 /// Returns `true` if the component or resource was added after the system last ran
2656 /// (or the system is running for the first time).
2657 #[inline]
2658 pub fn is_added(&self, last_run: Tick, this_run: Tick) -> bool {
2659 self.added.is_newer_than(last_run, this_run)
2660 }
2661
2662 /// Returns `true` if the component or resource was added or mutably dereferenced after the system last ran
2663 /// (or the system is running for the first time).
2664 #[inline]
2665 pub fn is_changed(&self, last_run: Tick, this_run: Tick) -> bool {
2666 self.changed.is_newer_than(last_run, this_run)
2667 }
2668
2669 /// Creates a new instance with the same change tick for `added` and `changed`.
2670 pub fn new(change_tick: Tick) -> Self {
2671 Self {
2672 added: change_tick,
2673 changed: change_tick,
2674 }
2675 }
2676
2677 /// Manually sets the change tick.
2678 ///
2679 /// This is normally done automatically via the [`DerefMut`] implementation
2680 /// on [`Mut<T>`](crate::change_detection::Mut), [`ResMut<T>`](crate::change_detection::ResMut), etc.
2681 /// However, components and resources that make use of interior mutability might require manual updates.
2682 ///
2683 /// # Example
2684 /// ```no_run
2685 /// # use bevy_ecs::{world::World, component::ComponentTicks};
2686 /// let world: World = unimplemented!();
2687 /// let component_ticks: ComponentTicks = unimplemented!();
2688 ///
2689 /// component_ticks.set_changed(world.read_change_tick());
2690 /// ```
2691 #[inline]
2692 pub fn set_changed(&mut self, change_tick: Tick) {
2693 self.changed = change_tick;
2694 }
2695}
2696
2697/// A [`SystemParam`] that provides access to the [`ComponentId`] for a specific component type.
2698///
2699/// # Example
2700/// ```
2701/// # use bevy_ecs::{system::Local, component::{Component, ComponentId, ComponentIdFor}};
2702/// #[derive(Component)]
2703/// struct Player;
2704/// fn my_system(component_id: ComponentIdFor<Player>) {
2705/// let component_id: ComponentId = component_id.get();
2706/// // ...
2707/// }
2708/// ```
2709#[derive(SystemParam)]
2710pub struct ComponentIdFor<'s, T: Component>(Local<'s, InitComponentId<T>>);
2711
2712impl<T: Component> ComponentIdFor<'_, T> {
2713 /// Gets the [`ComponentId`] for the type `T`.
2714 #[inline]
2715 pub fn get(&self) -> ComponentId {
2716 **self
2717 }
2718}
2719
2720impl<T: Component> Deref for ComponentIdFor<'_, T> {
2721 type Target = ComponentId;
2722 fn deref(&self) -> &Self::Target {
2723 &self.0.component_id
2724 }
2725}
2726
2727impl<T: Component> From<ComponentIdFor<'_, T>> for ComponentId {
2728 #[inline]
2729 fn from(to_component_id: ComponentIdFor<T>) -> ComponentId {
2730 *to_component_id
2731 }
2732}
2733
2734/// Initializes the [`ComponentId`] for a specific type when used with [`FromWorld`].
2735struct InitComponentId<T: Component> {
2736 component_id: ComponentId,
2737 marker: PhantomData<T>,
2738}
2739
2740impl<T: Component> FromWorld for InitComponentId<T> {
2741 fn from_world(world: &mut World) -> Self {
2742 Self {
2743 component_id: world.register_component::<T>(),
2744 marker: PhantomData,
2745 }
2746 }
2747}
2748
2749/// An error returned when the registration of a required component fails.
2750#[derive(Error, Debug)]
2751#[non_exhaustive]
2752pub enum RequiredComponentsError {
2753 /// The component is already a directly required component for the requiree.
2754 #[error("Component {0:?} already directly requires component {1:?}")]
2755 DuplicateRegistration(ComponentId, ComponentId),
2756 /// An archetype with the component that requires other components already exists
2757 #[error("An archetype with the component {0:?} that requires other components already exists")]
2758 ArchetypeExists(ComponentId),
2759}
2760
2761/// A Required Component constructor. See [`Component`] for details.
2762#[derive(Clone)]
2763pub struct RequiredComponentConstructor(
2764 pub Arc<dyn Fn(&mut Table, &mut SparseSets, Tick, TableRow, Entity, MaybeLocation)>,
2765);
2766
2767impl RequiredComponentConstructor {
2768 /// # Safety
2769 /// This is intended to only be called in the context of [`BundleInfo::write_components`] to initialized required components.
2770 /// Calling it _anywhere else_ should be considered unsafe.
2771 ///
2772 /// `table_row` and `entity` must correspond to a valid entity that currently needs a component initialized via the constructor stored
2773 /// on this [`RequiredComponentConstructor`]. The stored constructor must correspond to a component on `entity` that needs initialization.
2774 /// `table` and `sparse_sets` must correspond to storages on a world where `entity` needs this required component initialized.
2775 ///
2776 /// Again, don't call this anywhere but [`BundleInfo::write_components`].
2777 pub(crate) unsafe fn initialize(
2778 &self,
2779 table: &mut Table,
2780 sparse_sets: &mut SparseSets,
2781 change_tick: Tick,
2782 table_row: TableRow,
2783 entity: Entity,
2784 caller: MaybeLocation,
2785 ) {
2786 (self.0)(table, sparse_sets, change_tick, table_row, entity, caller);
2787 }
2788}
2789
2790/// Metadata associated with a required component. See [`Component`] for details.
2791#[derive(Clone)]
2792pub struct RequiredComponent {
2793 /// The constructor used for the required component.
2794 pub constructor: RequiredComponentConstructor,
2795
2796 /// The depth of the component requirement in the requirement hierarchy for this component.
2797 /// This is used for determining which constructor is used in cases where there are duplicate requires.
2798 ///
2799 /// For example, consider the inheritance tree `X -> Y -> Z`, where `->` indicates a requirement.
2800 /// `X -> Y` and `Y -> Z` are direct requirements with a depth of 0, while `Z` is only indirectly
2801 /// required for `X` with a depth of `1`.
2802 ///
2803 /// In cases where there are multiple conflicting requirements with the same depth, a higher priority
2804 /// will be given to components listed earlier in the `require` attribute, or to the latest added requirement
2805 /// if registered at runtime.
2806 pub inheritance_depth: u16,
2807}
2808
2809/// The collection of metadata for components that are required for a given component.
2810///
2811/// For more information, see the "Required Components" section of [`Component`].
2812#[derive(Default, Clone)]
2813pub struct RequiredComponents(pub(crate) HashMap<ComponentId, RequiredComponent>);
2814
2815impl Debug for RequiredComponents {
2816 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2817 f.debug_tuple("RequiredComponents")
2818 .field(&self.0.keys())
2819 .finish()
2820 }
2821}
2822
2823impl RequiredComponents {
2824 /// Registers a required component.
2825 ///
2826 /// If the component is already registered, it will be overwritten if the given inheritance depth
2827 /// is smaller than the depth of the existing registration. Otherwise, the new registration will be ignored.
2828 ///
2829 /// # Safety
2830 ///
2831 /// `component_id` must match the type initialized by `constructor`.
2832 /// `constructor` _must_ initialize a component for `component_id` in such a way that
2833 /// matches the storage type of the component. It must only use the given `table_row` or `Entity` to
2834 /// initialize the storage for `component_id` corresponding to the given entity.
2835 pub unsafe fn register_dynamic_with(
2836 &mut self,
2837 component_id: ComponentId,
2838 inheritance_depth: u16,
2839 constructor: impl FnOnce() -> RequiredComponentConstructor,
2840 ) {
2841 let entry = self.0.entry(component_id);
2842 match entry {
2843 bevy_platform::collections::hash_map::Entry::Occupied(mut occupied) => {
2844 let current = occupied.get_mut();
2845 if current.inheritance_depth > inheritance_depth {
2846 *current = RequiredComponent {
2847 constructor: constructor(),
2848 inheritance_depth,
2849 }
2850 }
2851 }
2852 bevy_platform::collections::hash_map::Entry::Vacant(vacant) => {
2853 vacant.insert(RequiredComponent {
2854 constructor: constructor(),
2855 inheritance_depth,
2856 });
2857 }
2858 }
2859 }
2860
2861 /// Registers a required component.
2862 ///
2863 /// If the component is already registered, it will be overwritten if the given inheritance depth
2864 /// is smaller than the depth of the existing registration. Otherwise, the new registration will be ignored.
2865 pub fn register<C: Component>(
2866 &mut self,
2867 components: &mut ComponentsRegistrator,
2868 constructor: fn() -> C,
2869 inheritance_depth: u16,
2870 ) {
2871 let component_id = components.register_component::<C>();
2872 self.register_by_id(component_id, constructor, inheritance_depth);
2873 }
2874
2875 /// Registers the [`Component`] with the given ID as required if it exists.
2876 ///
2877 /// If the component is already registered, it will be overwritten if the given inheritance depth
2878 /// is smaller than the depth of the existing registration. Otherwise, the new registration will be ignored.
2879 pub fn register_by_id<C: Component>(
2880 &mut self,
2881 component_id: ComponentId,
2882 constructor: fn() -> C,
2883 inheritance_depth: u16,
2884 ) {
2885 let erased = || {
2886 RequiredComponentConstructor({
2887 // `portable-atomic-util` `Arc` is not able to coerce an unsized
2888 // type like `std::sync::Arc` can. Creating a `Box` first does the
2889 // coercion.
2890 //
2891 // This would be resolved by https://github.com/rust-lang/rust/issues/123430
2892
2893 #[cfg(not(target_has_atomic = "ptr"))]
2894 use alloc::boxed::Box;
2895
2896 type Constructor = dyn for<'a, 'b> Fn(
2897 &'a mut Table,
2898 &'b mut SparseSets,
2899 Tick,
2900 TableRow,
2901 Entity,
2902 MaybeLocation,
2903 );
2904
2905 #[cfg(not(target_has_atomic = "ptr"))]
2906 type Intermediate<T> = Box<T>;
2907
2908 #[cfg(target_has_atomic = "ptr")]
2909 type Intermediate<T> = Arc<T>;
2910
2911 let boxed: Intermediate<Constructor> = Intermediate::new(
2912 move |table, sparse_sets, change_tick, table_row, entity, caller| {
2913 OwningPtr::make(constructor(), |ptr| {
2914 // SAFETY: This will only be called in the context of `BundleInfo::write_components`, which will
2915 // pass in a valid table_row and entity requiring a C constructor
2916 // C::STORAGE_TYPE is the storage type associated with `component_id` / `C`
2917 // `ptr` points to valid `C` data, which matches the type associated with `component_id`
2918 unsafe {
2919 BundleInfo::initialize_required_component(
2920 table,
2921 sparse_sets,
2922 change_tick,
2923 table_row,
2924 entity,
2925 component_id,
2926 C::STORAGE_TYPE,
2927 ptr,
2928 caller,
2929 );
2930 }
2931 });
2932 },
2933 );
2934
2935 Arc::from(boxed)
2936 })
2937 };
2938
2939 // SAFETY:
2940 // `component_id` matches the type initialized by the `erased` constructor above.
2941 // `erased` initializes a component for `component_id` in such a way that
2942 // matches the storage type of the component. It only uses the given `table_row` or `Entity` to
2943 // initialize the storage corresponding to the given entity.
2944 unsafe { self.register_dynamic_with(component_id, inheritance_depth, erased) };
2945 }
2946
2947 /// Iterates the ids of all required components. This includes recursive required components.
2948 pub fn iter_ids(&self) -> impl Iterator<Item = ComponentId> + '_ {
2949 self.0.keys().copied()
2950 }
2951
2952 /// Removes components that are explicitly provided in a given [`Bundle`]. These components should
2953 /// be logically treated as normal components, not "required components".
2954 ///
2955 /// [`Bundle`]: crate::bundle::Bundle
2956 pub(crate) fn remove_explicit_components(&mut self, components: &[ComponentId]) {
2957 for component in components {
2958 self.0.remove(component);
2959 }
2960 }
2961
2962 /// Merges `required_components` into this collection. This only inserts a required component
2963 /// if it _did not already exist_ *or* if the required component is more specific than the existing one
2964 /// (in other words, if the inheritance depth is smaller).
2965 ///
2966 /// See [`register_dynamic_with`](Self::register_dynamic_with) for details.
2967 pub(crate) fn merge(&mut self, required_components: &RequiredComponents) {
2968 for (
2969 component_id,
2970 RequiredComponent {
2971 constructor,
2972 inheritance_depth,
2973 },
2974 ) in required_components.0.iter()
2975 {
2976 // SAFETY: This exact registration must have been done on `required_components`, so safety is ensured by that caller.
2977 unsafe {
2978 self.register_dynamic_with(*component_id, *inheritance_depth, || {
2979 constructor.clone()
2980 });
2981 }
2982 }
2983 }
2984}
2985
2986// NOTE: This should maybe be private, but it is currently public so that `bevy_ecs_macros` can use it.
2987// This exists as a standalone function instead of being inlined into the component derive macro so as
2988// to reduce the amount of generated code.
2989#[doc(hidden)]
2990pub fn enforce_no_required_components_recursion(
2991 components: &Components,
2992 recursion_check_stack: &[ComponentId],
2993) {
2994 if let Some((&requiree, check)) = recursion_check_stack.split_last() {
2995 if let Some(direct_recursion) = check
2996 .iter()
2997 .position(|&id| id == requiree)
2998 .map(|index| index == check.len() - 1)
2999 {
3000 panic!(
3001 "Recursive required components detected: {}\nhelp: {}",
3002 recursion_check_stack
3003 .iter()
3004 .map(|id| format!("{}", ShortName(&components.get_name(*id).unwrap())))
3005 .collect::<Vec<_>>()
3006 .join(" → "),
3007 if direct_recursion {
3008 format!(
3009 "Remove require({}).",
3010 ShortName(&components.get_name(requiree).unwrap())
3011 )
3012 } else {
3013 "If this is intentional, consider merging the components.".into()
3014 }
3015 );
3016 }
3017 }
3018}
3019
3020/// Component [clone handler function](ComponentCloneFn) implemented using the [`Clone`] trait.
3021/// Can be [set](Component::clone_behavior) as clone handler for the specific component it is implemented for.
3022/// It will panic if set as handler for any other component.
3023///
3024pub fn component_clone_via_clone<C: Clone + Component>(
3025 source: &SourceComponent,
3026 ctx: &mut ComponentCloneCtx,
3027) {
3028 if let Some(component) = source.read::<C>() {
3029 ctx.write_target_component(component.clone());
3030 }
3031}
3032
3033/// Component [clone handler function](ComponentCloneFn) implemented using reflect.
3034/// Can be [set](Component::clone_behavior) as clone handler for any registered component,
3035/// but only reflected components will be cloned.
3036///
3037/// To clone a component using this handler, the following must be true:
3038/// - World has [`AppTypeRegistry`](crate::reflect::AppTypeRegistry)
3039/// - Component has [`TypeId`]
3040/// - Component is registered
3041/// - Component has [`ReflectFromPtr`](bevy_reflect::ReflectFromPtr) registered
3042/// - Component can be cloned via [`PartialReflect::reflect_clone`] _or_ has one of the following registered: [`ReflectFromReflect`](bevy_reflect::ReflectFromReflect),
3043/// [`ReflectDefault`](bevy_reflect::std_traits::ReflectDefault), [`ReflectFromWorld`](crate::reflect::ReflectFromWorld)
3044///
3045/// If any of the conditions is not satisfied, the component will be skipped.
3046///
3047/// See [`EntityClonerBuilder`](crate::entity::EntityClonerBuilder) for details.
3048///
3049/// [`PartialReflect::reflect_clone`]: bevy_reflect::PartialReflect::reflect_clone
3050#[cfg(feature = "bevy_reflect")]
3051pub fn component_clone_via_reflect(source: &SourceComponent, ctx: &mut ComponentCloneCtx) {
3052 let Some(app_registry) = ctx.type_registry().cloned() else {
3053 return;
3054 };
3055 let registry = app_registry.read();
3056 let Some(source_component_reflect) = source.read_reflect(®istry) else {
3057 return;
3058 };
3059 let component_info = ctx.component_info();
3060 // checked in read_source_component_reflect
3061 let type_id = component_info.type_id().unwrap();
3062
3063 // Try to clone using `reflect_clone`
3064 if let Ok(mut component) = source_component_reflect.reflect_clone() {
3065 if let Some(reflect_component) =
3066 registry.get_type_data::<crate::reflect::ReflectComponent>(type_id)
3067 {
3068 reflect_component.map_entities(&mut *component, ctx.entity_mapper());
3069 }
3070 drop(registry);
3071
3072 ctx.write_target_component_reflect(component);
3073 return;
3074 }
3075
3076 // Try to clone using ReflectFromReflect
3077 if let Some(reflect_from_reflect) =
3078 registry.get_type_data::<bevy_reflect::ReflectFromReflect>(type_id)
3079 {
3080 if let Some(mut component) =
3081 reflect_from_reflect.from_reflect(source_component_reflect.as_partial_reflect())
3082 {
3083 if let Some(reflect_component) =
3084 registry.get_type_data::<crate::reflect::ReflectComponent>(type_id)
3085 {
3086 reflect_component.map_entities(&mut *component, ctx.entity_mapper());
3087 }
3088 drop(registry);
3089
3090 ctx.write_target_component_reflect(component);
3091 return;
3092 }
3093 }
3094 // Else, try to clone using ReflectDefault
3095 if let Some(reflect_default) =
3096 registry.get_type_data::<bevy_reflect::std_traits::ReflectDefault>(type_id)
3097 {
3098 let mut component = reflect_default.default();
3099 component.apply(source_component_reflect.as_partial_reflect());
3100 drop(registry);
3101 ctx.write_target_component_reflect(component);
3102 return;
3103 }
3104 // Otherwise, try to clone using ReflectFromWorld
3105 if let Some(reflect_from_world) =
3106 registry.get_type_data::<crate::reflect::ReflectFromWorld>(type_id)
3107 {
3108 let reflect_from_world = reflect_from_world.clone();
3109 let source_component_cloned = source_component_reflect.to_dynamic();
3110 let component_layout = component_info.layout();
3111 let target = ctx.target();
3112 let component_id = ctx.component_id();
3113 drop(registry);
3114 ctx.queue_deferred(move |world: &mut World, mapper: &mut dyn EntityMapper| {
3115 let mut component = reflect_from_world.from_world(world);
3116 assert_eq!(type_id, (*component).type_id());
3117 component.apply(source_component_cloned.as_partial_reflect());
3118 if let Some(reflect_component) = app_registry
3119 .read()
3120 .get_type_data::<crate::reflect::ReflectComponent>(type_id)
3121 {
3122 reflect_component.map_entities(&mut *component, mapper);
3123 }
3124 // SAFETY:
3125 // - component_id is from the same world as target entity
3126 // - component is a valid value represented by component_id
3127 unsafe {
3128 let raw_component_ptr =
3129 core::ptr::NonNull::new_unchecked(Box::into_raw(component).cast::<u8>());
3130 world
3131 .entity_mut(target)
3132 .insert_by_id(component_id, OwningPtr::new(raw_component_ptr));
3133
3134 if component_layout.size() > 0 {
3135 // Ensure we don't attempt to deallocate zero-sized components
3136 alloc::alloc::dealloc(raw_component_ptr.as_ptr(), component_layout);
3137 }
3138 }
3139 });
3140 }
3141}
3142
3143/// Noop implementation of component clone handler function.
3144///
3145/// See [`EntityClonerBuilder`](crate::entity::EntityClonerBuilder) for details.
3146pub fn component_clone_ignore(_source: &SourceComponent, _ctx: &mut ComponentCloneCtx) {}
3147
3148/// Wrapper for components clone specialization using autoderef.
3149#[doc(hidden)]
3150pub struct DefaultCloneBehaviorSpecialization<T>(PhantomData<T>);
3151
3152impl<T> Default for DefaultCloneBehaviorSpecialization<T> {
3153 fn default() -> Self {
3154 Self(PhantomData)
3155 }
3156}
3157
3158/// Base trait for components clone specialization using autoderef.
3159#[doc(hidden)]
3160pub trait DefaultCloneBehaviorBase {
3161 fn default_clone_behavior(&self) -> ComponentCloneBehavior;
3162}
3163impl<C> DefaultCloneBehaviorBase for DefaultCloneBehaviorSpecialization<C> {
3164 fn default_clone_behavior(&self) -> ComponentCloneBehavior {
3165 ComponentCloneBehavior::Default
3166 }
3167}
3168
3169/// Specialized trait for components clone specialization using autoderef.
3170#[doc(hidden)]
3171pub trait DefaultCloneBehaviorViaClone {
3172 fn default_clone_behavior(&self) -> ComponentCloneBehavior;
3173}
3174impl<C: Clone + Component> DefaultCloneBehaviorViaClone for &DefaultCloneBehaviorSpecialization<C> {
3175 fn default_clone_behavior(&self) -> ComponentCloneBehavior {
3176 ComponentCloneBehavior::clone::<C>()
3177 }
3178}