use alloc::vec::Vec;1use bevy_ecs::{2change_detection::{DetectChangesMut, MutUntyped},3component::Tick,4event::{BufferedEvent, EventKey, Events},5resource::Resource,6world::World,7};89#[doc(hidden)]10struct RegisteredEvent {11event_key: EventKey,12// Required to flush the secondary buffer and drop events even if left unchanged.13previously_updated: bool,14// SAFETY: The `EventKey`'s component ID and the function must be used to fetch the Events<T> resource15// of the same type initialized in `register_event`, or improper type casts will occur.16update: unsafe fn(MutUntyped),17}1819/// A registry of all of the [`Events`] in the [`World`], used by [`event_update_system`](crate::event::update::event_update_system)20/// to update all of the events.21#[derive(Resource, Default)]22pub struct EventRegistry {23/// Should the events be updated?24///25/// This field is generally automatically updated by the [`signal_event_update_system`](crate::event::update::signal_event_update_system).26pub should_update: ShouldUpdateEvents,27event_updates: Vec<RegisteredEvent>,28}2930/// Controls whether or not the events in an [`EventRegistry`] should be updated.31#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]32pub enum ShouldUpdateEvents {33/// Without any fixed timestep, events should always be updated each frame.34#[default]35Always,36/// We need to wait until at least one pass of the fixed update schedules to update the events.37Waiting,38/// At least one pass of the fixed update schedules has occurred, and the events are ready to be updated.39Ready,40}4142impl EventRegistry {43/// Registers an event type to be updated in a given [`World`]44///45/// If no instance of the [`EventRegistry`] exists in the world, this will add one - otherwise it will use46/// the existing instance.47pub fn register_event<T: BufferedEvent>(world: &mut World) {48// By initializing the resource here, we can be sure that it is present,49// and receive the correct, up-to-date `ComponentId` even if it was previously removed.50let component_id = world.init_resource::<Events<T>>();51let mut registry = world.get_resource_or_init::<Self>();52registry.event_updates.push(RegisteredEvent {53event_key: EventKey(component_id),54previously_updated: false,55update: |ptr| {56// SAFETY: The resource was initialized with the type Events<T>.57unsafe { ptr.with_type::<Events<T>>() }58.bypass_change_detection()59.update();60},61});62}6364/// Updates all of the registered events in the World.65pub fn run_updates(&mut self, world: &mut World, last_change_tick: Tick) {66for registered_event in &mut self.event_updates {67// Bypass the type ID -> Component ID lookup with the cached component ID.68if let Some(events) =69world.get_resource_mut_by_id(registered_event.event_key.component_id())70{71let has_changed = events.has_changed_since(last_change_tick);72if registered_event.previously_updated || has_changed {73// SAFETY: The update function pointer is called with the resource74// fetched from the same component ID.75unsafe { (registered_event.update)(events) };76// Always set to true if the events have changed, otherwise disable running on the second invocation77// to wait for more changes.78registered_event.previously_updated =79has_changed || !registered_event.previously_updated;80}81}82}83}8485/// Removes an event from the world and its associated [`EventRegistry`].86pub fn deregister_events<T: BufferedEvent>(world: &mut World) {87let component_id = world.init_resource::<Events<T>>();88let mut registry = world.get_resource_or_init::<Self>();89registry90.event_updates91.retain(|e| e.event_key.component_id() != component_id);92world.remove_resource::<Events<T>>();93}94}959697