//! Types for declaring and storing [`Component`]s.12mod clone;3mod constants;4mod info;5mod register;6mod required;78pub use clone::*;9pub use constants::*;10pub use info::*;11pub use register::*;12pub use required::*;1314use crate::{15entity::EntityMapper,16lifecycle::ComponentHook,17relationship::ComponentRelationshipAccessor,18system::{Local, SystemParam},19world::{FromWorld, World},20};21pub use bevy_ecs_macros::Component;22use core::{fmt::Debug, marker::PhantomData, ops::Deref};2324/// A data type that can be used to store data for an [entity].25///26/// `Component` is a [derivable trait]: this means that a data type can implement it by applying a `#[derive(Component)]` attribute to it.27/// However, components must always satisfy the `Send + Sync + 'static` trait bounds.28///29/// [entity]: crate::entity30/// [derivable trait]: https://doc.rust-lang.org/book/appendix-03-derivable-traits.html31///32/// # Examples33///34/// 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.35/// The following examples show how components are laid out in code.36///37/// ```38/// # use bevy_ecs::component::Component;39/// # struct Color;40/// #41/// // A component can contain data...42/// #[derive(Component)]43/// struct LicensePlate(String);44///45/// // ... but it can also be a zero-sized marker.46/// #[derive(Component)]47/// struct Car;48///49/// // Components can also be structs with named fields...50/// #[derive(Component)]51/// struct VehiclePerformance {52/// acceleration: f32,53/// top_speed: f32,54/// handling: f32,55/// }56///57/// // ... or enums.58/// #[derive(Component)]59/// enum WheelCount {60/// Two,61/// Three,62/// Four,63/// }64/// ```65///66/// # Component and data access67///68/// Components can be marked as immutable by adding the `#[component(immutable)]`69/// attribute when using the derive macro.70/// See the documentation for [`ComponentMutability`] for more details around this71/// feature.72///73/// See the [`entity`] module level documentation to learn how to add or remove components from an entity.74///75/// See the documentation for [`Query`] to learn how to access component data from a system.76///77/// [`entity`]: crate::entity#usage78/// [`Query`]: crate::system::Query79/// [`ComponentMutability`]: crate::component::ComponentMutability80///81/// # Choosing a storage type82///83/// Components can be stored in the world using different strategies with their own performance implications.84/// By default, components are added to the [`Table`] storage, which is optimized for query iteration.85///86/// Alternatively, components can be added to the [`SparseSet`] storage, which is optimized for component insertion and removal.87/// This is achieved by adding an additional `#[component(storage = "SparseSet")]` attribute to the derive one:88///89/// ```90/// # use bevy_ecs::component::Component;91/// #92/// #[derive(Component)]93/// #[component(storage = "SparseSet")]94/// struct ComponentA;95/// ```96///97/// [`Table`]: crate::storage::Table98/// [`SparseSet`]: crate::storage::SparseSet99///100/// # Required Components101///102/// Components can specify Required Components. If some [`Component`] `A` requires [`Component`] `B`, then when `A` is inserted,103/// `B` will _also_ be initialized and inserted (if it was not manually specified).104///105/// The [`Default`] constructor will be used to initialize the component, by default:106///107/// ```108/// # use bevy_ecs::prelude::*;109/// #[derive(Component)]110/// #[require(B)]111/// struct A;112///113/// #[derive(Component, Default, PartialEq, Eq, Debug)]114/// struct B(usize);115///116/// # let mut world = World::default();117/// // This will implicitly also insert B with the Default constructor118/// let id = world.spawn(A).id();119/// assert_eq!(&B(0), world.entity(id).get::<B>().unwrap());120///121/// // This will _not_ implicitly insert B, because it was already provided122/// world.spawn((A, B(11)));123/// ```124///125/// Components can have more than one required component:126///127/// ```128/// # use bevy_ecs::prelude::*;129/// #[derive(Component)]130/// #[require(B, C)]131/// struct A;132///133/// #[derive(Component, Default, PartialEq, Eq, Debug)]134/// #[require(C)]135/// struct B(usize);136///137/// #[derive(Component, Default, PartialEq, Eq, Debug)]138/// struct C(u32);139///140/// # let mut world = World::default();141/// // This will implicitly also insert B and C with their Default constructors142/// let id = world.spawn(A).id();143/// assert_eq!(&B(0), world.entity(id).get::<B>().unwrap());144/// assert_eq!(&C(0), world.entity(id).get::<C>().unwrap());145/// ```146///147/// You can define inline component values that take the following forms:148/// ```149/// # use bevy_ecs::prelude::*;150/// #[derive(Component)]151/// #[require(152/// B(1), // tuple structs153/// C { // named-field structs154/// x: 1,155/// ..Default::default()156/// },157/// D::One, // enum variants158/// E::ONE, // associated consts159/// F::new(1) // constructors160/// )]161/// struct A;162///163/// #[derive(Component, PartialEq, Eq, Debug)]164/// struct B(u8);165///166/// #[derive(Component, PartialEq, Eq, Debug, Default)]167/// struct C {168/// x: u8,169/// y: u8,170/// }171///172/// #[derive(Component, PartialEq, Eq, Debug)]173/// enum D {174/// Zero,175/// One,176/// }177///178/// #[derive(Component, PartialEq, Eq, Debug)]179/// struct E(u8);180///181/// impl E {182/// pub const ONE: Self = Self(1);183/// }184///185/// #[derive(Component, PartialEq, Eq, Debug)]186/// struct F(u8);187///188/// impl F {189/// fn new(value: u8) -> Self {190/// Self(value)191/// }192/// }193///194/// # let mut world = World::default();195/// let id = world.spawn(A).id();196/// assert_eq!(&B(1), world.entity(id).get::<B>().unwrap());197/// assert_eq!(&C { x: 1, y: 0 }, world.entity(id).get::<C>().unwrap());198/// assert_eq!(&D::One, world.entity(id).get::<D>().unwrap());199/// assert_eq!(&E(1), world.entity(id).get::<E>().unwrap());200/// assert_eq!(&F(1), world.entity(id).get::<F>().unwrap());201/// ````202///203///204/// You can also define arbitrary expressions by using `=`205///206/// ```207/// # use bevy_ecs::prelude::*;208/// #[derive(Component)]209/// #[require(C = init_c())]210/// struct A;211///212/// #[derive(Component, PartialEq, Eq, Debug)]213/// #[require(C = C(20))]214/// struct B;215///216/// #[derive(Component, PartialEq, Eq, Debug)]217/// struct C(usize);218///219/// fn init_c() -> C {220/// C(10)221/// }222///223/// # let mut world = World::default();224/// // This will implicitly also insert C with the init_c() constructor225/// let id = world.spawn(A).id();226/// assert_eq!(&C(10), world.entity(id).get::<C>().unwrap());227///228/// // This will implicitly also insert C with the `|| C(20)` constructor closure229/// let id = world.spawn(B).id();230/// assert_eq!(&C(20), world.entity(id).get::<C>().unwrap());231/// ```232///233/// Required components are _recursive_. This means, if a Required Component has required components,234/// those components will _also_ be inserted if they are missing:235///236/// ```237/// # use bevy_ecs::prelude::*;238/// #[derive(Component)]239/// #[require(B)]240/// struct A;241///242/// #[derive(Component, Default, PartialEq, Eq, Debug)]243/// #[require(C)]244/// struct B(usize);245///246/// #[derive(Component, Default, PartialEq, Eq, Debug)]247/// struct C(u32);248///249/// # let mut world = World::default();250/// // This will implicitly also insert B and C with their Default constructors251/// let id = world.spawn(A).id();252/// assert_eq!(&B(0), world.entity(id).get::<B>().unwrap());253/// assert_eq!(&C(0), world.entity(id).get::<C>().unwrap());254/// ```255///256/// Note that cycles in the "component require tree" will result in stack overflows when attempting to257/// insert a component.258///259/// This "multiple inheritance" pattern does mean that it is possible to have duplicate requires for a given type260/// at different levels of the inheritance tree:261///262/// ```263/// # use bevy_ecs::prelude::*;264/// #[derive(Component)]265/// struct X(usize);266///267/// #[derive(Component, Default)]268/// #[require(X(1))]269/// struct Y;270///271/// #[derive(Component)]272/// #[require(273/// Y,274/// X(2),275/// )]276/// struct Z;277///278/// # let mut world = World::default();279/// // In this case, the x2 constructor is used for X280/// let id = world.spawn(Z).id();281/// assert_eq!(2, world.entity(id).get::<X>().unwrap().0);282/// ```283///284/// In general, this shouldn't happen often, but when it does the algorithm for choosing the constructor from the tree is simple and predictable:285/// 1. A constructor from a direct `#[require()]`, if one exists, is selected with priority.286/// 2. Otherwise, perform a Depth First Search on the tree of requirements and select the first one found.287///288/// From a user perspective, just think about this as the following:289/// 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.290/// 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.291///292/// ## Registering required components at runtime293///294/// In most cases, required components should be registered using the `require` attribute as shown above.295/// However, in some cases, it may be useful to register required components at runtime.296///297/// This can be done through [`World::register_required_components`] or [`World::register_required_components_with`]298/// for the [`Default`] and custom constructors respectively:299///300/// ```301/// # use bevy_ecs::prelude::*;302/// #[derive(Component)]303/// struct A;304///305/// #[derive(Component, Default, PartialEq, Eq, Debug)]306/// struct B(usize);307///308/// #[derive(Component, PartialEq, Eq, Debug)]309/// struct C(u32);310///311/// # let mut world = World::default();312/// // Register B as required by A and C as required by B.313/// world.register_required_components::<A, B>();314/// world.register_required_components_with::<B, C>(|| C(2));315///316/// // This will implicitly also insert B with its Default constructor317/// // and C with the custom constructor defined by B.318/// let id = world.spawn(A).id();319/// assert_eq!(&B(0), world.entity(id).get::<B>().unwrap());320/// assert_eq!(&C(2), world.entity(id).get::<C>().unwrap());321/// ```322///323/// Similar rules as before apply to duplicate requires fer a given type at different levels324/// of the inheritance tree. `A` requiring `C` directly would take precedence over indirectly325/// requiring it through `A` requiring `B` and `B` requiring `C`.326///327/// Unlike with the `require` attribute, directly requiring the same component multiple times328/// for the same component will result in a panic. This is done to prevent conflicting constructors329/// and confusing ordering dependencies.330///331/// Note that requirements must currently be registered before the requiring component is inserted332/// into the world for the first time. Registering requirements after this will lead to a panic.333///334/// # Relationships between Entities335///336/// Sometimes it is useful to define relationships between entities. A common example is the337/// parent / child relationship. Since Components are how data is stored for Entities, one might338/// naturally think to create a Component which has a field of type [`Entity`].339///340/// To facilitate this pattern, Bevy provides the [`Relationship`](`crate::relationship::Relationship`)341/// trait. You can derive the [`Relationship`](`crate::relationship::Relationship`) and342/// [`RelationshipTarget`](`crate::relationship::RelationshipTarget`) traits in addition to the343/// Component trait in order to implement data driven relationships between entities, see the trait344/// docs for more details.345///346/// In addition, Bevy provides canonical implementations of the parent / child relationship via the347/// [`ChildOf`](crate::hierarchy::ChildOf) [`Relationship`](crate::relationship::Relationship) and348/// the [`Children`](crate::hierarchy::Children)349/// [`RelationshipTarget`](crate::relationship::RelationshipTarget).350///351/// # Adding component's hooks352///353/// See [`ComponentHooks`] for a detailed explanation of component's hooks.354///355/// Alternatively to the example shown in [`ComponentHooks`]' documentation, hooks can be configured using following attributes:356/// - `#[component(on_add = on_add_function)]`357/// - `#[component(on_insert = on_insert_function)]`358/// - `#[component(on_replace = on_replace_function)]`359/// - `#[component(on_remove = on_remove_function)]`360///361/// ```362/// # use bevy_ecs::component::Component;363/// # use bevy_ecs::lifecycle::HookContext;364/// # use bevy_ecs::world::DeferredWorld;365/// # use bevy_ecs::entity::Entity;366/// # use bevy_ecs::component::ComponentId;367/// # use core::panic::Location;368/// #369/// #[derive(Component)]370/// #[component(on_add = my_on_add_hook)]371/// #[component(on_insert = my_on_insert_hook)]372/// // Another possible way of configuring hooks:373/// // #[component(on_add = my_on_add_hook, on_insert = my_on_insert_hook)]374/// //375/// // We don't have a replace or remove hook, so we can leave them out:376/// // #[component(on_replace = my_on_replace_hook, on_remove = my_on_remove_hook)]377/// struct ComponentA;378///379/// fn my_on_add_hook(world: DeferredWorld, context: HookContext) {380/// // ...381/// }382///383/// // You can also destructure items directly in the signature384/// fn my_on_insert_hook(world: DeferredWorld, HookContext { caller, .. }: HookContext) {385/// // ...386/// }387/// ```388///389/// This also supports function calls that yield closures390///391/// ```392/// # use bevy_ecs::component::Component;393/// # use bevy_ecs::lifecycle::HookContext;394/// # use bevy_ecs::world::DeferredWorld;395/// #396/// #[derive(Component)]397/// #[component(on_add = my_msg_hook("hello"))]398/// #[component(on_despawn = my_msg_hook("yoink"))]399/// struct ComponentA;400///401/// // a hook closure generating function402/// fn my_msg_hook(message: &'static str) -> impl Fn(DeferredWorld, HookContext) {403/// move |_world, _ctx| {404/// println!("{message}");405/// }406/// }407///408/// ```409///410/// A hook's function path can be elided if it is `Self::on_add`, `Self::on_insert` etc.411/// ```412/// # use bevy_ecs::lifecycle::HookContext;413/// # use bevy_ecs::prelude::*;414/// # use bevy_ecs::world::DeferredWorld;415/// #416/// #[derive(Component, Debug)]417/// #[component(on_add)]418/// struct DoubleOnSpawn(usize);419///420/// impl DoubleOnSpawn {421/// fn on_add(mut world: DeferredWorld, context: HookContext) {422/// let mut entity = world.get_mut::<Self>(context.entity).unwrap();423/// entity.0 *= 2;424/// }425/// }426/// #427/// # let mut world = World::new();428/// # let entity = world.spawn(DoubleOnSpawn(2));429/// # assert_eq!(entity.get::<DoubleOnSpawn>().unwrap().0, 4);430/// ```431///432/// # Setting the clone behavior433///434/// You can specify how the [`Component`] is cloned when deriving it.435///436/// Your options are the functions and variants of [`ComponentCloneBehavior`]437/// See [Clone Behaviors section of `EntityCloner`](crate::entity::EntityCloner#clone-behaviors) to understand how this affects handler priority.438/// ```439/// # use bevy_ecs::prelude::*;440///441/// #[derive(Component)]442/// #[component(clone_behavior = Ignore)]443/// struct MyComponent;444///445/// ```446///447/// # Implementing the trait for foreign types448///449/// 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.450/// This means that it is not possible to directly have a type defined in a third party library as a component.451/// This important limitation can be easily worked around using the [newtype pattern]:452/// this makes it possible to locally define and implement `Component` for a tuple struct that wraps the foreign type.453/// The following example gives a demonstration of this pattern.454///455/// ```456/// // `Component` is defined in the `bevy_ecs` crate.457/// use bevy_ecs::component::Component;458///459/// // `Duration` is defined in the `std` crate.460/// use std::time::Duration;461///462/// // It is not possible to implement `Component` for `Duration` from this position, as they are463/// // both foreign items, defined in an external crate. However, nothing prevents to define a new464/// // `Cooldown` type that wraps `Duration`. As `Cooldown` is defined in a local crate, it is465/// // possible to implement `Component` for it.466/// #[derive(Component)]467/// struct Cooldown(Duration);468/// ```469///470/// [orphan rule]: https://doc.rust-lang.org/book/ch10-02-traits.html#implementing-a-trait-on-a-type471/// [newtype pattern]: https://doc.rust-lang.org/book/ch19-03-advanced-traits.html#using-the-newtype-pattern-to-implement-external-traits-on-external-types472///473/// # `!Sync` Components474/// A `!Sync` type cannot implement `Component`. However, it is possible to wrap a `Send` but not `Sync`475/// type in [`SyncCell`] or the currently unstable [`Exclusive`] to make it `Sync`. This forces only476/// having mutable access (`&mut T` only, never `&T`), but makes it safe to reference across multiple477/// threads.478///479/// This will fail to compile since `RefCell` is `!Sync`.480/// ```compile_fail481/// # use std::cell::RefCell;482/// # use bevy_ecs::component::Component;483/// #[derive(Component)]484/// struct NotSync {485/// counter: RefCell<usize>,486/// }487/// ```488///489/// This will compile since the `RefCell` is wrapped with `SyncCell`.490/// ```491/// # use std::cell::RefCell;492/// # use bevy_ecs::component::Component;493/// use bevy_platform::cell::SyncCell;494///495/// // This will compile.496/// #[derive(Component)]497/// struct ActuallySync {498/// counter: SyncCell<RefCell<usize>>,499/// }500/// ```501///502/// [`SyncCell`]: bevy_platform::cell::SyncCell503/// [`Exclusive`]: https://doc.rust-lang.org/nightly/std/sync/struct.Exclusive.html504/// [`ComponentHooks`]: crate::lifecycle::ComponentHooks505#[diagnostic::on_unimplemented(506message = "`{Self}` is not a `Component`",507label = "invalid `Component`",508note = "consider annotating `{Self}` with `#[derive(Component)]`"509)]510pub trait Component: Send + Sync + 'static {511/// A constant indicating the storage type used for this component.512const STORAGE_TYPE: StorageType;513514/// A marker type to assist Bevy with determining if this component is515/// mutable, or immutable. Mutable components will have [`Component<Mutability = Mutable>`],516/// while immutable components will instead have [`Component<Mutability = Immutable>`].517///518/// * For a component to be mutable, this type must be [`Mutable`].519/// * For a component to be immutable, this type must be [`Immutable`].520type Mutability: ComponentMutability;521522/// Gets the `on_add` [`ComponentHook`] for this [`Component`] if one is defined.523fn on_add() -> Option<ComponentHook> {524None525}526527/// Gets the `on_insert` [`ComponentHook`] for this [`Component`] if one is defined.528fn on_insert() -> Option<ComponentHook> {529None530}531532/// Gets the `on_replace` [`ComponentHook`] for this [`Component`] if one is defined.533fn on_replace() -> Option<ComponentHook> {534None535}536537/// Gets the `on_remove` [`ComponentHook`] for this [`Component`] if one is defined.538fn on_remove() -> Option<ComponentHook> {539None540}541542/// Gets the `on_despawn` [`ComponentHook`] for this [`Component`] if one is defined.543fn on_despawn() -> Option<ComponentHook> {544None545}546547/// Registers required components.548///549/// # Safety550///551/// - `_required_components` must only contain components valid in `_components`.552fn register_required_components(553_component_id: ComponentId,554_required_components: &mut RequiredComponentsRegistrator,555) {556}557558/// Called when registering this component, allowing to override clone function (or disable cloning altogether) for this component.559///560/// See [Clone Behaviors section of `EntityCloner`](crate::entity::EntityCloner#clone-behaviors) to understand how this affects handler priority.561#[inline]562fn clone_behavior() -> ComponentCloneBehavior {563ComponentCloneBehavior::Default564}565566/// Maps the entities on this component using the given [`EntityMapper`]. This is used to remap entities in contexts like scenes and entity cloning.567/// When deriving [`Component`], this is populated by annotating fields containing entities with `#[entities]`568///569/// ```570/// # use bevy_ecs::{component::Component, entity::Entity};571/// #[derive(Component)]572/// struct Inventory {573/// #[entities]574/// items: Vec<Entity>575/// }576/// ```577///578/// Fields with `#[entities]` must implement [`MapEntities`](crate::entity::MapEntities).579///580/// Bevy provides various implementations of [`MapEntities`](crate::entity::MapEntities), so that arbitrary combinations like these are supported with `#[entities]`:581///582/// ```rust583/// # use bevy_ecs::{component::Component, entity::Entity};584/// #[derive(Component)]585/// struct Inventory {586/// #[entities]587/// items: Vec<Option<Entity>>588/// }589/// ```590///591/// You might need more specialized logic. A likely cause of this is your component contains collections of entities that592/// don't implement [`MapEntities`](crate::entity::MapEntities). In that case, you can annotate your component with593/// `#[component(map_entities)]`. Using this attribute, you must implement `MapEntities` for the594/// component itself, and this method will simply call that implementation.595///596/// ```597/// # use bevy_ecs::{component::Component, entity::{Entity, MapEntities, EntityMapper}};598/// # use std::collections::HashMap;599/// #[derive(Component)]600/// #[component(map_entities)]601/// struct Inventory {602/// items: HashMap<Entity, usize>603/// }604///605/// impl MapEntities for Inventory {606/// fn map_entities<M: EntityMapper>(&mut self, entity_mapper: &mut M) {607/// self.items = self.items608/// .drain()609/// .map(|(id, count)|(entity_mapper.get_mapped(id), count))610/// .collect();611/// }612/// }613/// # let a = Entity::from_bits(0x1_0000_0001);614/// # let b = Entity::from_bits(0x1_0000_0002);615/// # let mut inv = Inventory { items: Default::default() };616/// # inv.items.insert(a, 10);617/// # <Inventory as Component>::map_entities(&mut inv, &mut (a,b));618/// # assert_eq!(inv.items.get(&b), Some(&10));619/// ````620///621/// Alternatively, you can specify the path to a function with `#[component(map_entities = function_path)]`, similar to component hooks.622/// In this case, the inputs of the function should mirror the inputs to this method, with the second parameter being generic.623///624/// ```625/// # use bevy_ecs::{component::Component, entity::{Entity, MapEntities, EntityMapper}};626/// # use std::collections::HashMap;627/// #[derive(Component)]628/// #[component(map_entities = map_the_map)]629/// // Also works: map_the_map::<M> or map_the_map::<_>630/// struct Inventory {631/// items: HashMap<Entity, usize>632/// }633///634/// fn map_the_map<M: EntityMapper>(inv: &mut Inventory, entity_mapper: &mut M) {635/// inv.items = inv.items636/// .drain()637/// .map(|(id, count)|(entity_mapper.get_mapped(id), count))638/// .collect();639/// }640/// # let a = Entity::from_bits(0x1_0000_0001);641/// # let b = Entity::from_bits(0x1_0000_0002);642/// # let mut inv = Inventory { items: Default::default() };643/// # inv.items.insert(a, 10);644/// # <Inventory as Component>::map_entities(&mut inv, &mut (a,b));645/// # assert_eq!(inv.items.get(&b), Some(&10));646/// ````647///648/// You can use the turbofish (`::<A,B,C>`) to specify parameters when a function is generic, using either M or _ for the type of the mapper parameter.649#[inline]650fn map_entities<E: EntityMapper>(_this: &mut Self, _mapper: &mut E) {}651652/// Returns [`ComponentRelationshipAccessor`] required for working with relationships in dynamic contexts.653///654/// If component is not a [`Relationship`](crate::relationship::Relationship) or [`RelationshipTarget`](crate::relationship::RelationshipTarget), this should return `None`.655fn relationship_accessor() -> Option<ComponentRelationshipAccessor<Self>> {656None657}658}659660mod private {661pub trait Seal {}662}663664/// The mutability option for a [`Component`]. This can either be:665/// * [`Mutable`]666/// * [`Immutable`]667///668/// This is controlled through either [`Component::Mutability`] or `#[component(immutable)]`669/// when using the derive macro.670///671/// Immutable components are guaranteed to never have an exclusive reference,672/// `&mut ...`, created while inserted onto an entity.673/// In all other ways, they are identical to mutable components.674/// This restriction allows hooks to observe all changes made to an immutable675/// component, effectively turning the `Insert` and `Replace` hooks into a676/// `OnMutate` hook.677/// This is not practical for mutable components, as the runtime cost of invoking678/// a hook for every exclusive reference created would be far too high.679///680/// # Examples681///682/// ```rust683/// # use bevy_ecs::component::Component;684/// #685/// #[derive(Component)]686/// #[component(immutable)]687/// struct ImmutableFoo;688/// ```689pub trait ComponentMutability: private::Seal + 'static {690/// Boolean to indicate if this mutability setting implies a mutable or immutable691/// component.692const MUTABLE: bool;693}694695/// Parameter indicating a [`Component`] is immutable.696///697/// See [`ComponentMutability`] for details.698pub struct Immutable;699700impl private::Seal for Immutable {}701702impl ComponentMutability for Immutable {703const MUTABLE: bool = false;704}705706/// Parameter indicating a [`Component`] is mutable.707///708/// See [`ComponentMutability`] for details.709pub struct Mutable;710711impl private::Seal for Mutable {}712713impl ComponentMutability for Mutable {714const MUTABLE: bool = true;715}716717/// The storage used for a specific component type.718///719/// # Examples720/// The [`StorageType`] for a component is configured via the derive attribute721///722/// ```723/// # use bevy_ecs::{prelude::*, component::*};724/// #[derive(Component)]725/// #[component(storage = "SparseSet")]726/// struct A;727/// ```728#[derive(Debug, Copy, Clone, Default, Eq, PartialEq)]729pub enum StorageType {730/// Provides fast and cache-friendly iteration, but slower addition and removal of components.731/// This is the default storage type.732#[default]733Table,734/// Provides fast addition and removal of components, but slower iteration.735SparseSet,736}737738/// A [`SystemParam`] that provides access to the [`ComponentId`] for a specific component type.739///740/// # Example741/// ```742/// # use bevy_ecs::{system::Local, component::{Component, ComponentId, ComponentIdFor}};743/// #[derive(Component)]744/// struct Player;745/// fn my_system(component_id: ComponentIdFor<Player>) {746/// let component_id: ComponentId = component_id.get();747/// // ...748/// }749/// ```750#[derive(SystemParam)]751pub struct ComponentIdFor<'s, T: Component>(Local<'s, InitComponentId<T>>);752753impl<T: Component> ComponentIdFor<'_, T> {754/// Gets the [`ComponentId`] for the type `T`.755#[inline]756pub fn get(&self) -> ComponentId {757**self758}759}760761impl<T: Component> Deref for ComponentIdFor<'_, T> {762type Target = ComponentId;763fn deref(&self) -> &Self::Target {764&self.0.component_id765}766}767768impl<T: Component> From<ComponentIdFor<'_, T>> for ComponentId {769#[inline]770fn from(to_component_id: ComponentIdFor<T>) -> ComponentId {771*to_component_id772}773}774775/// Initializes the [`ComponentId`] for a specific type when used with [`FromWorld`].776struct InitComponentId<T: Component> {777component_id: ComponentId,778marker: PhantomData<T>,779}780781impl<T: Component> FromWorld for InitComponentId<T> {782fn from_world(world: &mut World) -> Self {783Self {784component_id: world.register_component::<T>(),785marker: PhantomData,786}787}788}789790791