//! This module contains various tools to allow you to react to component insertion or removal,1//! as well as entity spawning and despawning.2//!3//! There are four main ways to react to these lifecycle events:4//!5//! 1. Using component hooks, which act as inherent constructors and destructors for components.6//! 2. Using [observers], which are a user-extensible way to respond to events, including component lifecycle events.7//! 3. Using the [`RemovedComponents`] system parameter, which offers an event-style interface.8//! 4. Using the [`Added`] query filter, which checks each component to see if it has been added since the last time a system ran.9//!10//! [observers]: crate::observer11//! [`Added`]: crate::query::Added12//!13//! # Types of lifecycle events14//!15//! There are five types of lifecycle events, split into two categories. First, we have lifecycle events that are triggered16//! when a component is added to an entity:17//!18//! - [`Add`]: Triggered when a component is added to an entity that did not already have it.19//! - [`Insert`]: Triggered when a component is added to an entity, regardless of whether it already had it.20//!21//! When both events occur, [`Add`] hooks are evaluated before [`Insert`].22//!23//! Next, we have lifecycle events that are triggered when a component is removed from an entity:24//!25//! - [`Replace`]: Triggered when a component is removed from an entity, regardless if it is then replaced with a new value.26//! - [`Remove`]: Triggered when a component is removed from an entity and not replaced, before the component is removed.27//! - [`Despawn`]: Triggered for each component on an entity when it is despawned.28//!29//! [`Replace`] hooks are evaluated before [`Remove`], then finally [`Despawn`] hooks are evaluated.30//!31//! [`Add`] and [`Remove`] are counterparts: they are only triggered when a component is added or removed32//! from an entity in such a way as to cause a change in the component's presence on that entity.33//! Similarly, [`Insert`] and [`Replace`] are counterparts: they are triggered when a component is added or replaced34//! on an entity, regardless of whether this results in a change in the component's presence on that entity.35//!36//! To reliably synchronize data structures using with component lifecycle events,37//! you can combine [`Insert`] and [`Replace`] to fully capture any changes to the data.38//! This is particularly useful in combination with immutable components,39//! to avoid any lifecycle-bypassing mutations.40//!41//! ## Lifecycle events and component types42//!43//! Despite the absence of generics, each lifecycle event is associated with a specific component.44//! When defining a component hook for a [`Component`] type, that component is used.45//! When observers watch lifecycle events, the `B: Bundle` generic is used.46//!47//! Each of these lifecycle events also corresponds to a fixed [`ComponentId`],48//! which are assigned during [`World`] initialization.49//! For example, [`Add`] corresponds to [`ADD`].50//! This is used to skip [`TypeId`](core::any::TypeId) lookups in hot paths.51use crate::{52change_detection::MaybeLocation,53component::{Component, ComponentId, ComponentIdFor, Tick},54entity::Entity,55event::{56BufferedEvent, EntityComponentsTrigger, EntityEvent, EventCursor, EventId, EventIterator,57EventIteratorWithId, EventKey, Events,58},59query::FilteredAccessSet,60relationship::RelationshipHookMode,61storage::SparseSet,62system::{Local, ReadOnlySystemParam, SystemMeta, SystemParam},63world::{unsafe_world_cell::UnsafeWorldCell, DeferredWorld, World},64};6566use derive_more::derive::Into;6768#[cfg(feature = "bevy_reflect")]69use bevy_reflect::Reflect;70use core::{71fmt::Debug,72iter,73marker::PhantomData,74ops::{Deref, DerefMut},75option,76};7778/// The type used for [`Component`] lifecycle hooks such as `on_add`, `on_insert` or `on_remove`.79pub type ComponentHook = for<'w> fn(DeferredWorld<'w>, HookContext);8081/// Context provided to a [`ComponentHook`].82#[derive(Clone, Copy, Debug)]83pub struct HookContext {84/// The [`Entity`] this hook was invoked for.85pub entity: Entity,86/// The [`ComponentId`] this hook was invoked for.87pub component_id: ComponentId,88/// The caller location is `Some` if the `track_caller` feature is enabled.89pub caller: MaybeLocation,90/// Configures how relationship hooks will run91pub relationship_hook_mode: RelationshipHookMode,92}9394/// [`World`]-mutating functions that run as part of lifecycle events of a [`Component`].95///96/// Hooks are functions that run when a component is added, overwritten, or removed from an entity.97/// These are intended to be used for structural side effects that need to happen when a component is added or removed,98/// and are not intended for general-purpose logic.99///100/// For example, you might use a hook to update a cached index when a component is added,101/// to clean up resources when a component is removed,102/// or to keep hierarchical data structures across entities in sync.103///104/// This information is stored in the [`ComponentInfo`](crate::component::ComponentInfo) of the associated component.105///106/// There are two ways of configuring hooks for a component:107/// 1. Defining the relevant hooks on the [`Component`] implementation108/// 2. Using the [`World::register_component_hooks`] method109///110/// # Example111///112/// ```113/// use bevy_ecs::prelude::*;114/// use bevy_platform::collections::HashSet;115///116/// #[derive(Component)]117/// struct MyTrackedComponent;118///119/// #[derive(Resource, Default)]120/// struct TrackedEntities(HashSet<Entity>);121///122/// let mut world = World::new();123/// world.init_resource::<TrackedEntities>();124///125/// // No entities with `MyTrackedComponent` have been added yet, so we can safely add component hooks126/// let mut tracked_component_query = world.query::<&MyTrackedComponent>();127/// assert!(tracked_component_query.iter(&world).next().is_none());128///129/// world.register_component_hooks::<MyTrackedComponent>().on_add(|mut world, context| {130/// let mut tracked_entities = world.resource_mut::<TrackedEntities>();131/// tracked_entities.0.insert(context.entity);132/// });133///134/// world.register_component_hooks::<MyTrackedComponent>().on_remove(|mut world, context| {135/// let mut tracked_entities = world.resource_mut::<TrackedEntities>();136/// tracked_entities.0.remove(&context.entity);137/// });138///139/// let entity = world.spawn(MyTrackedComponent).id();140/// let tracked_entities = world.resource::<TrackedEntities>();141/// assert!(tracked_entities.0.contains(&entity));142///143/// world.despawn(entity);144/// let tracked_entities = world.resource::<TrackedEntities>();145/// assert!(!tracked_entities.0.contains(&entity));146/// ```147#[derive(Debug, Clone, Default)]148pub struct ComponentHooks {149pub(crate) on_add: Option<ComponentHook>,150pub(crate) on_insert: Option<ComponentHook>,151pub(crate) on_replace: Option<ComponentHook>,152pub(crate) on_remove: Option<ComponentHook>,153pub(crate) on_despawn: Option<ComponentHook>,154}155156impl ComponentHooks {157pub(crate) fn update_from_component<C: Component + ?Sized>(&mut self) -> &mut Self {158if let Some(hook) = C::on_add() {159self.on_add(hook);160}161if let Some(hook) = C::on_insert() {162self.on_insert(hook);163}164if let Some(hook) = C::on_replace() {165self.on_replace(hook);166}167if let Some(hook) = C::on_remove() {168self.on_remove(hook);169}170if let Some(hook) = C::on_despawn() {171self.on_despawn(hook);172}173174self175}176177/// Register a [`ComponentHook`] that will be run when this component is added to an entity.178/// An `on_add` hook will always run before `on_insert` hooks. Spawning an entity counts as179/// adding all of its components.180///181/// # Panics182///183/// Will panic if the component already has an `on_add` hook184pub fn on_add(&mut self, hook: ComponentHook) -> &mut Self {185self.try_on_add(hook)186.expect("Component already has an on_add hook")187}188189/// Register a [`ComponentHook`] that will be run when this component is added (with `.insert`)190/// or replaced.191///192/// An `on_insert` hook always runs after any `on_add` hooks (if the entity didn't already have the component).193///194/// # Warning195///196/// The hook won't run if the component is already present and is only mutated, such as in a system via a query.197/// As a result, this needs to be combined with immutable components to serve as a mechanism for reliably updating indexes and other caches.198///199/// # Panics200///201/// Will panic if the component already has an `on_insert` hook202pub fn on_insert(&mut self, hook: ComponentHook) -> &mut Self {203self.try_on_insert(hook)204.expect("Component already has an on_insert hook")205}206207/// Register a [`ComponentHook`] that will be run when this component is about to be dropped,208/// such as being replaced (with `.insert`) or removed.209///210/// If this component is inserted onto an entity that already has it, this hook will run before the value is replaced,211/// allowing access to the previous data just before it is dropped.212/// This hook does *not* run if the entity did not already have this component.213///214/// An `on_replace` hook always runs before any `on_remove` hooks (if the component is being removed from the entity).215///216/// # Warning217///218/// The hook won't run if the component is already present and is only mutated, such as in a system via a query.219/// As a result, this needs to be combined with immutable components to serve as a mechanism for reliably updating indexes and other caches.220///221/// # Panics222///223/// Will panic if the component already has an `on_replace` hook224pub fn on_replace(&mut self, hook: ComponentHook) -> &mut Self {225self.try_on_replace(hook)226.expect("Component already has an on_replace hook")227}228229/// Register a [`ComponentHook`] that will be run when this component is removed from an entity.230/// Despawning an entity counts as removing all of its components.231///232/// # Panics233///234/// Will panic if the component already has an `on_remove` hook235pub fn on_remove(&mut self, hook: ComponentHook) -> &mut Self {236self.try_on_remove(hook)237.expect("Component already has an on_remove hook")238}239240/// Register a [`ComponentHook`] that will be run for each component on an entity when it is despawned.241///242/// # Panics243///244/// Will panic if the component already has an `on_despawn` hook245pub fn on_despawn(&mut self, hook: ComponentHook) -> &mut Self {246self.try_on_despawn(hook)247.expect("Component already has an on_despawn hook")248}249250/// Attempt to register a [`ComponentHook`] that will be run when this component is added to an entity.251///252/// This is a fallible version of [`Self::on_add`].253///254/// Returns `None` if the component already has an `on_add` hook.255pub fn try_on_add(&mut self, hook: ComponentHook) -> Option<&mut Self> {256if self.on_add.is_some() {257return None;258}259self.on_add = Some(hook);260Some(self)261}262263/// Attempt to register a [`ComponentHook`] that will be run when this component is added (with `.insert`)264///265/// This is a fallible version of [`Self::on_insert`].266///267/// Returns `None` if the component already has an `on_insert` hook.268pub fn try_on_insert(&mut self, hook: ComponentHook) -> Option<&mut Self> {269if self.on_insert.is_some() {270return None;271}272self.on_insert = Some(hook);273Some(self)274}275276/// Attempt to register a [`ComponentHook`] that will be run when this component is replaced (with `.insert`) or removed277///278/// This is a fallible version of [`Self::on_replace`].279///280/// Returns `None` if the component already has an `on_replace` hook.281pub fn try_on_replace(&mut self, hook: ComponentHook) -> Option<&mut Self> {282if self.on_replace.is_some() {283return None;284}285self.on_replace = Some(hook);286Some(self)287}288289/// Attempt to register a [`ComponentHook`] that will be run when this component is removed from an entity.290///291/// This is a fallible version of [`Self::on_remove`].292///293/// Returns `None` if the component already has an `on_remove` hook.294pub fn try_on_remove(&mut self, hook: ComponentHook) -> Option<&mut Self> {295if self.on_remove.is_some() {296return None;297}298self.on_remove = Some(hook);299Some(self)300}301302/// Attempt to register a [`ComponentHook`] that will be run for each component on an entity when it is despawned.303///304/// This is a fallible version of [`Self::on_despawn`].305///306/// Returns `None` if the component already has an `on_despawn` hook.307pub fn try_on_despawn(&mut self, hook: ComponentHook) -> Option<&mut Self> {308if self.on_despawn.is_some() {309return None;310}311self.on_despawn = Some(hook);312Some(self)313}314}315316/// [`EventKey`] for [`Add`]317pub const ADD: EventKey = EventKey(ComponentId::new(0));318/// [`EventKey`] for [`Insert`]319pub const INSERT: EventKey = EventKey(ComponentId::new(1));320/// [`EventKey`] for [`Replace`]321pub const REPLACE: EventKey = EventKey(ComponentId::new(2));322/// [`EventKey`] for [`Remove`]323pub const REMOVE: EventKey = EventKey(ComponentId::new(3));324/// [`EventKey`] for [`Despawn`]325pub const DESPAWN: EventKey = EventKey(ComponentId::new(4));326327/// Trigger emitted when a component is inserted onto an entity that does not already have that328/// component. Runs before `Insert`.329/// See [`crate::lifecycle::ComponentHooks::on_add`] for more information.330#[derive(Debug, Clone, EntityEvent)]331#[entity_event(trigger = EntityComponentsTrigger<'a>)]332#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]333#[cfg_attr(feature = "bevy_reflect", reflect(Debug))]334#[doc(alias = "OnAdd")]335pub struct Add {336/// The entity this component was added to.337pub entity: Entity,338}339340/// Trigger emitted when a component is inserted, regardless of whether or not the entity already341/// had that component. Runs after `Add`, if it ran.342/// See [`crate::lifecycle::ComponentHooks::on_insert`] for more information.343#[derive(Debug, Clone, EntityEvent)]344#[entity_event(trigger = EntityComponentsTrigger<'a>)]345#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]346#[cfg_attr(feature = "bevy_reflect", reflect(Debug))]347#[doc(alias = "OnInsert")]348pub struct Insert {349/// The entity this component was inserted into.350pub entity: Entity,351}352353/// Trigger emitted when a component is removed from an entity, regardless354/// of whether or not it is later replaced.355///356/// Runs before the value is replaced, so you can still access the original component data.357/// See [`crate::lifecycle::ComponentHooks::on_replace`] for more information.358#[derive(Debug, Clone, EntityEvent)]359#[entity_event(trigger = EntityComponentsTrigger<'a>)]360#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]361#[cfg_attr(feature = "bevy_reflect", reflect(Debug))]362#[doc(alias = "OnReplace")]363pub struct Replace {364/// The entity that held this component before it was replaced.365pub entity: Entity,366}367368/// Trigger emitted when a component is removed from an entity, and runs before the component is369/// removed, so you can still access the component data.370/// See [`crate::lifecycle::ComponentHooks::on_remove`] for more information.371#[derive(Debug, Clone, EntityEvent)]372#[entity_event(trigger = EntityComponentsTrigger<'a>)]373#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]374#[cfg_attr(feature = "bevy_reflect", reflect(Debug))]375#[doc(alias = "OnRemove")]376pub struct Remove {377/// The entity this component was removed from.378pub entity: Entity,379}380381/// [`EntityEvent`] emitted for each component on an entity when it is despawned.382/// See [`crate::lifecycle::ComponentHooks::on_despawn`] for more information.383#[derive(Debug, Clone, EntityEvent)]384#[entity_event(trigger = EntityComponentsTrigger<'a>)]385#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]386#[cfg_attr(feature = "bevy_reflect", reflect(Debug))]387#[doc(alias = "OnDespawn")]388pub struct Despawn {389/// The entity that held this component before it was despawned.390pub entity: Entity,391}392393/// Deprecated in favor of [`Add`].394#[deprecated(since = "0.17.0", note = "Renamed to `Add`.")]395pub type OnAdd = Add;396397/// Deprecated in favor of [`Insert`].398#[deprecated(since = "0.17.0", note = "Renamed to `Insert`.")]399pub type OnInsert = Insert;400401/// Deprecated in favor of [`Replace`].402#[deprecated(since = "0.17.0", note = "Renamed to `Replace`.")]403pub type OnReplace = Replace;404405/// Deprecated in favor of [`Remove`].406#[deprecated(since = "0.17.0", note = "Renamed to `Remove`.")]407pub type OnRemove = Remove;408409/// Deprecated in favor of [`Despawn`].410#[deprecated(since = "0.17.0", note = "Renamed to `Despawn`.")]411pub type OnDespawn = Despawn;412413/// Wrapper around [`Entity`] for [`RemovedComponents`].414/// Internally, `RemovedComponents` uses these as an `Events<RemovedComponentEntity>`.415#[derive(BufferedEvent, Debug, Clone, Into)]416#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]417#[cfg_attr(feature = "bevy_reflect", reflect(Debug, Clone))]418pub struct RemovedComponentEntity(Entity);419420/// Wrapper around a [`EventCursor<RemovedComponentEntity>`] so that we421/// can differentiate events between components.422#[derive(Debug)]423pub struct RemovedComponentReader<T>424where425T: Component,426{427reader: EventCursor<RemovedComponentEntity>,428marker: PhantomData<T>,429}430431impl<T: Component> Default for RemovedComponentReader<T> {432fn default() -> Self {433Self {434reader: Default::default(),435marker: PhantomData,436}437}438}439440impl<T: Component> Deref for RemovedComponentReader<T> {441type Target = EventCursor<RemovedComponentEntity>;442fn deref(&self) -> &Self::Target {443&self.reader444}445}446447impl<T: Component> DerefMut for RemovedComponentReader<T> {448fn deref_mut(&mut self) -> &mut Self::Target {449&mut self.reader450}451}452453/// Stores the [`RemovedComponents`] event buffers for all types of component in a given [`World`].454#[derive(Default, Debug)]455pub struct RemovedComponentEvents {456event_sets: SparseSet<ComponentId, Events<RemovedComponentEntity>>,457}458459impl RemovedComponentEvents {460/// Creates an empty storage buffer for component removal events.461pub fn new() -> Self {462Self::default()463}464465/// For each type of component, swaps the event buffers and clears the oldest event buffer.466/// In general, this should be called once per frame/update.467pub fn update(&mut self) {468for (_component_id, events) in self.event_sets.iter_mut() {469events.update();470}471}472473/// Returns an iterator over components and their entity events.474pub fn iter(&self) -> impl Iterator<Item = (&ComponentId, &Events<RemovedComponentEntity>)> {475self.event_sets.iter()476}477478/// Gets the event storage for a given component.479pub fn get(480&self,481component_id: impl Into<ComponentId>,482) -> Option<&Events<RemovedComponentEntity>> {483self.event_sets.get(component_id.into())484}485486/// Sends a removal event for the specified component.487#[deprecated(since = "0.17.0", note = "Use `RemovedComponentEvents:write` instead.")]488pub fn send(&mut self, component_id: impl Into<ComponentId>, entity: Entity) {489self.write(component_id, entity);490}491492/// Writes a removal event for the specified component.493pub fn write(&mut self, component_id: impl Into<ComponentId>, entity: Entity) {494self.event_sets495.get_or_insert_with(component_id.into(), Default::default)496.write(RemovedComponentEntity(entity));497}498}499500/// A [`SystemParam`] that yields entities that had their `T` [`Component`]501/// removed or have been despawned with it.502///503/// This acts effectively the same as an [`EventReader`](crate::event::EventReader).504///505/// Unlike hooks or observers (see the [lifecycle](crate) module docs),506/// this does not allow you to see which data existed before removal.507///508/// If you are using `bevy_ecs` as a standalone crate,509/// note that the [`RemovedComponents`] list will not be automatically cleared for you,510/// and will need to be manually flushed using [`World::clear_trackers`](World::clear_trackers).511///512/// For users of `bevy` and `bevy_app`, [`World::clear_trackers`](World::clear_trackers) is513/// automatically called by `bevy_app::App::update` and `bevy_app::SubApp::update`.514/// For the main world, this is delayed until after all `SubApp`s have run.515///516/// # Examples517///518/// Basic usage:519///520/// ```521/// # use bevy_ecs::component::Component;522/// # use bevy_ecs::system::IntoSystem;523/// # use bevy_ecs::lifecycle::RemovedComponents;524/// #525/// # #[derive(Component)]526/// # struct MyComponent;527/// fn react_on_removal(mut removed: RemovedComponents<MyComponent>) {528/// removed.read().for_each(|removed_entity| println!("{}", removed_entity));529/// }530/// # bevy_ecs::system::assert_is_system(react_on_removal);531/// ```532#[derive(SystemParam)]533pub struct RemovedComponents<'w, 's, T: Component> {534component_id: ComponentIdFor<'s, T>,535reader: Local<'s, RemovedComponentReader<T>>,536event_sets: &'w RemovedComponentEvents,537}538539/// Iterator over entities that had a specific component removed.540///541/// See [`RemovedComponents`].542pub type RemovedIter<'a> = iter::Map<543iter::Flatten<option::IntoIter<iter::Cloned<EventIterator<'a, RemovedComponentEntity>>>>,544fn(RemovedComponentEntity) -> Entity,545>;546547/// Iterator over entities that had a specific component removed.548///549/// See [`RemovedComponents`].550pub type RemovedIterWithId<'a> = iter::Map<551iter::Flatten<option::IntoIter<EventIteratorWithId<'a, RemovedComponentEntity>>>,552fn(553(&RemovedComponentEntity, EventId<RemovedComponentEntity>),554) -> (Entity, EventId<RemovedComponentEntity>),555>;556557fn map_id_events(558(entity, id): (&RemovedComponentEntity, EventId<RemovedComponentEntity>),559) -> (Entity, EventId<RemovedComponentEntity>) {560(entity.clone().into(), id)561}562563// For all practical purposes, the api surface of `RemovedComponents<T>`564// should be similar to `EventReader<T>` to reduce confusion.565impl<'w, 's, T: Component> RemovedComponents<'w, 's, T> {566/// Fetch underlying [`EventCursor`].567pub fn reader(&self) -> &EventCursor<RemovedComponentEntity> {568&self.reader569}570571/// Fetch underlying [`EventCursor`] mutably.572pub fn reader_mut(&mut self) -> &mut EventCursor<RemovedComponentEntity> {573&mut self.reader574}575576/// Fetch underlying [`Events`].577pub fn events(&self) -> Option<&Events<RemovedComponentEntity>> {578self.event_sets.get(self.component_id.get())579}580581/// Destructures to get a mutable reference to the `EventCursor`582/// and a reference to `Events`.583///584/// This is necessary since Rust can't detect destructuring through methods and most585/// usecases of the reader uses the `Events` as well.586pub fn reader_mut_with_events(587&mut self,588) -> Option<(589&mut RemovedComponentReader<T>,590&Events<RemovedComponentEntity>,591)> {592self.event_sets593.get(self.component_id.get())594.map(|events| (&mut *self.reader, events))595}596597/// Iterates over the events this [`RemovedComponents`] has not seen yet. This updates the598/// [`RemovedComponents`]'s event counter, which means subsequent event reads will not include events599/// that happened before now.600pub fn read(&mut self) -> RemovedIter<'_> {601self.reader_mut_with_events()602.map(|(reader, events)| reader.read(events).cloned())603.into_iter()604.flatten()605.map(RemovedComponentEntity::into)606}607608/// Like [`read`](Self::read), except also returning the [`EventId`] of the events.609pub fn read_with_id(&mut self) -> RemovedIterWithId<'_> {610self.reader_mut_with_events()611.map(|(reader, events)| reader.read_with_id(events))612.into_iter()613.flatten()614.map(map_id_events)615}616617/// Determines the number of removal events available to be read from this [`RemovedComponents`] without consuming any.618pub fn len(&self) -> usize {619self.events()620.map(|events| self.reader.len(events))621.unwrap_or(0)622}623624/// Returns `true` if there are no events available to read.625pub fn is_empty(&self) -> bool {626self.events()627.is_none_or(|events| self.reader.is_empty(events))628}629630/// Consumes all available events.631///632/// This means these events will not appear in calls to [`RemovedComponents::read()`] or633/// [`RemovedComponents::read_with_id()`] and [`RemovedComponents::is_empty()`] will return `true`.634pub fn clear(&mut self) {635if let Some((reader, events)) = self.reader_mut_with_events() {636reader.clear(events);637}638}639}640641// SAFETY: Only reads World removed component events642unsafe impl<'a> ReadOnlySystemParam for &'a RemovedComponentEvents {}643644// SAFETY: no component value access.645unsafe impl<'a> SystemParam for &'a RemovedComponentEvents {646type State = ();647type Item<'w, 's> = &'w RemovedComponentEvents;648649fn init_state(_world: &mut World) -> Self::State {}650651fn init_access(652_state: &Self::State,653_system_meta: &mut SystemMeta,654_component_access_set: &mut FilteredAccessSet,655_world: &mut World,656) {657}658659#[inline]660unsafe fn get_param<'w, 's>(661_state: &'s mut Self::State,662_system_meta: &SystemMeta,663world: UnsafeWorldCell<'w>,664_change_tick: Tick,665) -> Self::Item<'w, 's> {666world.removed_components()667}668}669670671