bevy_ecs/
event.rs

1//! Event handling types.
2
3use crate as bevy_ecs;
4#[cfg(feature = "multi_threaded")]
5use crate::batching::BatchingStrategy;
6use crate::change_detection::MutUntyped;
7use crate::{
8    change_detection::{DetectChangesMut, Mut},
9    component::{Component, ComponentId, Tick},
10    system::{Local, Res, ResMut, Resource, SystemParam},
11    world::World,
12};
13pub use bevy_ecs_macros::Event;
14use bevy_ecs_macros::SystemSet;
15#[cfg(feature = "bevy_reflect")]
16use bevy_reflect::Reflect;
17use bevy_utils::detailed_trace;
18use std::ops::{Deref, DerefMut};
19use std::{
20    cmp::Ordering,
21    fmt,
22    hash::{Hash, Hasher},
23    iter::Chain,
24    marker::PhantomData,
25    slice::Iter,
26};
27
28/// Something that "happens" and might be read / observed by app logic.
29///
30/// Events can be stored in an [`Events<E>`] resource
31/// You can conveniently access events using the [`EventReader`] and [`EventWriter`] system parameter.
32///
33/// Events can also be "triggered" on a [`World`], which will then cause any [`Observer`] of that trigger to run.
34///
35/// This trait can be derived.
36///
37/// Events implement the [`Component`] type (and they automatically do when they are derived). Events are (generally)
38/// not directly inserted as components. More often, the [`ComponentId`] is used to identify the event type within the
39/// context of the ECS.
40///
41/// Events must be thread-safe.
42///
43/// [`World`]: crate::world::World
44/// [`ComponentId`]: crate::component::ComponentId
45/// [`Observer`]: crate::observer::Observer
46#[diagnostic::on_unimplemented(
47    message = "`{Self}` is not an `Event`",
48    label = "invalid `Event`",
49    note = "consider annotating `{Self}` with `#[derive(Event)]`"
50)]
51pub trait Event: Component {}
52
53/// An `EventId` uniquely identifies an event stored in a specific [`World`].
54///
55/// An `EventId` can among other things be used to trace the flow of an event from the point it was
56/// sent to the point it was processed. `EventId`s increase monotonically by send order.
57///
58/// [`World`]: crate::world::World
59#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]
60pub struct EventId<E: Event> {
61    /// Uniquely identifies the event associated with this ID.
62    // This value corresponds to the order in which each event was added to the world.
63    pub id: usize,
64    #[cfg_attr(feature = "bevy_reflect", reflect(ignore))]
65    _marker: PhantomData<E>,
66}
67
68impl<E: Event> Copy for EventId<E> {}
69
70impl<E: Event> Clone for EventId<E> {
71    fn clone(&self) -> Self {
72        *self
73    }
74}
75
76impl<E: Event> fmt::Display for EventId<E> {
77    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
78        <Self as fmt::Debug>::fmt(self, f)
79    }
80}
81
82impl<E: Event> fmt::Debug for EventId<E> {
83    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
84        write!(
85            f,
86            "event<{}>#{}",
87            std::any::type_name::<E>().split("::").last().unwrap(),
88            self.id,
89        )
90    }
91}
92
93impl<E: Event> PartialEq for EventId<E> {
94    fn eq(&self, other: &Self) -> bool {
95        self.id == other.id
96    }
97}
98
99impl<E: Event> Eq for EventId<E> {}
100
101impl<E: Event> PartialOrd for EventId<E> {
102    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
103        Some(self.cmp(other))
104    }
105}
106
107impl<E: Event> Ord for EventId<E> {
108    fn cmp(&self, other: &Self) -> Ordering {
109        self.id.cmp(&other.id)
110    }
111}
112
113impl<E: Event> Hash for EventId<E> {
114    fn hash<H: Hasher>(&self, state: &mut H) {
115        Hash::hash(&self.id, state);
116    }
117}
118
119#[derive(Debug)]
120#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]
121struct EventInstance<E: Event> {
122    pub event_id: EventId<E>,
123    pub event: E,
124}
125
126/// An event collection that represents the events that occurred within the last two
127/// [`Events::update`] calls.
128/// Events can be written to using an [`EventWriter`]
129/// and are typically cheaply read using an [`EventReader`].
130///
131/// Each event can be consumed by multiple systems, in parallel,
132/// with consumption tracked by the [`EventReader`] on a per-system basis.
133///
134/// If no [ordering](https://github.com/bevyengine/bevy/blob/main/examples/ecs/ecs_guide.rs)
135/// is applied between writing and reading systems, there is a risk of a race condition.
136/// This means that whether the events arrive before or after the next [`Events::update`] is unpredictable.
137///
138/// This collection is meant to be paired with a system that calls
139/// [`Events::update`] exactly once per update/frame.
140///
141/// [`event_update_system`] is a system that does this, typically initialized automatically using
142/// [`add_event`](https://docs.rs/bevy/*/bevy/app/struct.App.html#method.add_event).
143/// [`EventReader`]s are expected to read events from this collection at least once per loop/frame.
144/// Events will persist across a single frame boundary and so ordering of event producers and
145/// consumers is not critical (although poorly-planned ordering may cause accumulating lag).
146/// If events are not handled by the end of the frame after they are updated, they will be
147/// dropped silently.
148///
149/// # Example
150/// ```
151/// use bevy_ecs::event::{Event, Events};
152///
153/// #[derive(Event)]
154/// struct MyEvent {
155///     value: usize
156/// }
157///
158/// // setup
159/// let mut events = Events::<MyEvent>::default();
160/// let mut reader = events.get_reader();
161///
162/// // run this once per update/frame
163/// events.update();
164///
165/// // somewhere else: send an event
166/// events.send(MyEvent { value: 1 });
167///
168/// // somewhere else: read the events
169/// for event in reader.read(&events) {
170///     assert_eq!(event.value, 1)
171/// }
172///
173/// // events are only processed once per reader
174/// assert_eq!(reader.read(&events).count(), 0);
175/// ```
176///
177/// # Details
178///
179/// [`Events`] is implemented using a variation of a double buffer strategy.
180/// Each call to [`update`](Events::update) swaps buffers and clears out the oldest one.
181/// - [`EventReader`]s will read events from both buffers.
182/// - [`EventReader`]s that read at least once per update will never drop events.
183/// - [`EventReader`]s that read once within two updates might still receive some events
184/// - [`EventReader`]s that read after two updates are guaranteed to drop all events that occurred
185/// before those updates.
186///
187/// The buffers in [`Events`] will grow indefinitely if [`update`](Events::update) is never called.
188///
189/// An alternative call pattern would be to call [`update`](Events::update)
190/// manually across frames to control when events are cleared.
191/// This complicates consumption and risks ever-expanding memory usage if not cleaned up,
192/// but can be done by adding your event as a resource instead of using
193/// [`add_event`](https://docs.rs/bevy/*/bevy/app/struct.App.html#method.add_event).
194///
195/// [Example usage.](https://github.com/bevyengine/bevy/blob/latest/examples/ecs/event.rs)
196/// [Example usage standalone.](https://github.com/bevyengine/bevy/blob/latest/crates/bevy_ecs/examples/events.rs)
197///
198#[derive(Debug, Resource)]
199#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]
200pub struct Events<E: Event> {
201    /// Holds the oldest still active events.
202    /// Note that `a.start_event_count + a.len()` should always be equal to `events_b.start_event_count`.
203    events_a: EventSequence<E>,
204    /// Holds the newer events.
205    events_b: EventSequence<E>,
206    event_count: usize,
207}
208
209// Derived Default impl would incorrectly require E: Default
210impl<E: Event> Default for Events<E> {
211    fn default() -> Self {
212        Self {
213            events_a: Default::default(),
214            events_b: Default::default(),
215            event_count: Default::default(),
216        }
217    }
218}
219
220impl<E: Event> Events<E> {
221    /// Returns the index of the oldest event stored in the event buffer.
222    pub fn oldest_event_count(&self) -> usize {
223        self.events_a
224            .start_event_count
225            .min(self.events_b.start_event_count)
226    }
227
228    /// "Sends" an `event` by writing it to the current event buffer. [`EventReader`]s can then read
229    /// the event.
230    /// This method returns the [ID](`EventId`) of the sent `event`.
231    pub fn send(&mut self, event: E) -> EventId<E> {
232        let event_id = EventId {
233            id: self.event_count,
234            _marker: PhantomData,
235        };
236        detailed_trace!("Events::send() -> id: {}", event_id);
237
238        let event_instance = EventInstance { event_id, event };
239
240        self.events_b.push(event_instance);
241        self.event_count += 1;
242
243        event_id
244    }
245
246    /// Sends a list of `events` all at once, which can later be read by [`EventReader`]s.
247    /// This is more efficient than sending each event individually.
248    /// This method returns the [IDs](`EventId`) of the sent `events`.
249    pub fn send_batch(&mut self, events: impl IntoIterator<Item = E>) -> SendBatchIds<E> {
250        let last_count = self.event_count;
251
252        self.extend(events);
253
254        SendBatchIds {
255            last_count,
256            event_count: self.event_count,
257            _marker: PhantomData,
258        }
259    }
260
261    /// Sends the default value of the event. Useful when the event is an empty struct.
262    /// This method returns the [ID](`EventId`) of the sent `event`.
263    pub fn send_default(&mut self) -> EventId<E>
264    where
265        E: Default,
266    {
267        self.send(Default::default())
268    }
269
270    /// Gets a new [`ManualEventReader`]. This will include all events already in the event buffers.
271    pub fn get_reader(&self) -> ManualEventReader<E> {
272        ManualEventReader::default()
273    }
274
275    /// Gets a new [`ManualEventReader`]. This will ignore all events already in the event buffers.
276    /// It will read all future events.
277    pub fn get_reader_current(&self) -> ManualEventReader<E> {
278        ManualEventReader {
279            last_event_count: self.event_count,
280            ..Default::default()
281        }
282    }
283
284    /// Swaps the event buffers and clears the oldest event buffer. In general, this should be
285    /// called once per frame/update.
286    ///
287    /// If you need access to the events that were removed, consider using [`Events::update_drain`].
288    pub fn update(&mut self) {
289        std::mem::swap(&mut self.events_a, &mut self.events_b);
290        self.events_b.clear();
291        self.events_b.start_event_count = self.event_count;
292        debug_assert_eq!(
293            self.events_a.start_event_count + self.events_a.len(),
294            self.events_b.start_event_count
295        );
296    }
297
298    /// Swaps the event buffers and drains the oldest event buffer, returning an iterator
299    /// of all events that were removed. In general, this should be called once per frame/update.
300    ///
301    /// If you do not need to take ownership of the removed events, use [`Events::update`] instead.
302    #[must_use = "If you do not need the returned events, call .update() instead."]
303    pub fn update_drain(&mut self) -> impl Iterator<Item = E> + '_ {
304        std::mem::swap(&mut self.events_a, &mut self.events_b);
305        let iter = self.events_b.events.drain(..);
306        self.events_b.start_event_count = self.event_count;
307        debug_assert_eq!(
308            self.events_a.start_event_count + self.events_a.len(),
309            self.events_b.start_event_count
310        );
311
312        iter.map(|e| e.event)
313    }
314
315    #[inline]
316    fn reset_start_event_count(&mut self) {
317        self.events_a.start_event_count = self.event_count;
318        self.events_b.start_event_count = self.event_count;
319    }
320
321    /// Removes all events.
322    #[inline]
323    pub fn clear(&mut self) {
324        self.reset_start_event_count();
325        self.events_a.clear();
326        self.events_b.clear();
327    }
328
329    /// Returns the number of events currently stored in the event buffer.
330    #[inline]
331    pub fn len(&self) -> usize {
332        self.events_a.len() + self.events_b.len()
333    }
334
335    /// Returns true if there are no events currently stored in the event buffer.
336    #[inline]
337    pub fn is_empty(&self) -> bool {
338        self.len() == 0
339    }
340
341    /// Creates a draining iterator that removes all events.
342    pub fn drain(&mut self) -> impl Iterator<Item = E> + '_ {
343        self.reset_start_event_count();
344
345        // Drain the oldest events first, then the newest
346        self.events_a
347            .drain(..)
348            .chain(self.events_b.drain(..))
349            .map(|i| i.event)
350    }
351
352    /// Iterates over events that happened since the last "update" call.
353    /// WARNING: You probably don't want to use this call. In most cases you should use an
354    /// [`EventReader`]. You should only use this if you know you only need to consume events
355    /// between the last `update()` call and your call to `iter_current_update_events`.
356    /// If events happen outside that window, they will not be handled. For example, any events that
357    /// happen after this call and before the next `update()` call will be dropped.
358    pub fn iter_current_update_events(&self) -> impl ExactSizeIterator<Item = &E> {
359        self.events_b.iter().map(|i| &i.event)
360    }
361
362    /// Get a specific event by id if it still exists in the events buffer.
363    pub fn get_event(&self, id: usize) -> Option<(&E, EventId<E>)> {
364        if id < self.oldest_id() {
365            return None;
366        }
367
368        let sequence = self.sequence(id);
369        let index = id.saturating_sub(sequence.start_event_count);
370
371        sequence
372            .get(index)
373            .map(|instance| (&instance.event, instance.event_id))
374    }
375
376    /// Oldest id still in the events buffer.
377    pub fn oldest_id(&self) -> usize {
378        self.events_a.start_event_count
379    }
380
381    /// Which event buffer is this event id a part of.
382    fn sequence(&self, id: usize) -> &EventSequence<E> {
383        if id < self.events_b.start_event_count {
384            &self.events_a
385        } else {
386            &self.events_b
387        }
388    }
389}
390
391impl<E: Event> Extend<E> for Events<E> {
392    fn extend<I>(&mut self, iter: I)
393    where
394        I: IntoIterator<Item = E>,
395    {
396        let old_count = self.event_count;
397        let mut event_count = self.event_count;
398        let events = iter.into_iter().map(|event| {
399            let event_id = EventId {
400                id: event_count,
401                _marker: PhantomData,
402            };
403            event_count += 1;
404            EventInstance { event_id, event }
405        });
406
407        self.events_b.extend(events);
408
409        if old_count != event_count {
410            detailed_trace!(
411                "Events::extend() -> ids: ({}..{})",
412                self.event_count,
413                event_count
414            );
415        }
416
417        self.event_count = event_count;
418    }
419}
420
421#[derive(Debug)]
422#[cfg_attr(feature = "bevy_reflect", derive(Reflect))]
423struct EventSequence<E: Event> {
424    events: Vec<EventInstance<E>>,
425    start_event_count: usize,
426}
427
428// Derived Default impl would incorrectly require E: Default
429impl<E: Event> Default for EventSequence<E> {
430    fn default() -> Self {
431        Self {
432            events: Default::default(),
433            start_event_count: Default::default(),
434        }
435    }
436}
437
438impl<E: Event> Deref for EventSequence<E> {
439    type Target = Vec<EventInstance<E>>;
440
441    fn deref(&self) -> &Self::Target {
442        &self.events
443    }
444}
445
446impl<E: Event> DerefMut for EventSequence<E> {
447    fn deref_mut(&mut self) -> &mut Self::Target {
448        &mut self.events
449    }
450}
451
452/// Reads events of type `T` in order and tracks which events have already been read.
453///
454/// # Concurrency
455///
456/// Unlike [`EventWriter<T>`], systems with `EventReader<T>` param can be executed concurrently
457/// (but not concurrently with `EventWriter<T>` systems for the same event type).
458#[derive(SystemParam, Debug)]
459pub struct EventReader<'w, 's, E: Event> {
460    reader: Local<'s, ManualEventReader<E>>,
461    events: Res<'w, Events<E>>,
462}
463
464impl<'w, 's, E: Event> EventReader<'w, 's, E> {
465    /// Iterates over the events this [`EventReader`] has not seen yet. This updates the
466    /// [`EventReader`]'s event counter, which means subsequent event reads will not include events
467    /// that happened before now.
468    pub fn read(&mut self) -> EventIterator<'_, E> {
469        self.reader.read(&self.events)
470    }
471
472    /// Like [`read`](Self::read), except also returning the [`EventId`] of the events.
473    pub fn read_with_id(&mut self) -> EventIteratorWithId<'_, E> {
474        self.reader.read_with_id(&self.events)
475    }
476
477    /// Returns a parallel iterator over the events this [`EventReader`] has not seen yet.
478    /// See also [`for_each`](EventParIter::for_each).
479    ///
480    /// # Example
481    /// ```
482    /// # use bevy_ecs::prelude::*;
483    /// # use std::sync::atomic::{AtomicUsize, Ordering};
484    ///
485    /// #[derive(Event)]
486    /// struct MyEvent {
487    ///     value: usize,
488    /// }
489    ///
490    /// #[derive(Resource, Default)]
491    /// struct Counter(AtomicUsize);
492    ///
493    /// // setup
494    /// let mut world = World::new();
495    /// world.init_resource::<Events<MyEvent>>();
496    /// world.insert_resource(Counter::default());
497    ///
498    /// let mut schedule = Schedule::default();
499    /// schedule.add_systems(|mut events: EventReader<MyEvent>, counter: Res<Counter>| {
500    ///     events.par_read().for_each(|MyEvent { value }| {
501    ///         counter.0.fetch_add(*value, Ordering::Relaxed);
502    ///     });
503    /// });
504    /// for value in 0..100 {
505    ///     world.send_event(MyEvent { value });
506    /// }
507    /// schedule.run(&mut world);
508    /// let Counter(counter) = world.remove_resource::<Counter>().unwrap();
509    /// // all events were processed
510    /// assert_eq!(counter.into_inner(), 4950);
511    /// ```
512    ///
513    #[cfg(feature = "multi_threaded")]
514    pub fn par_read(&mut self) -> EventParIter<'_, E> {
515        self.reader.par_read(&self.events)
516    }
517
518    /// Determines the number of events available to be read from this [`EventReader`] without consuming any.
519    pub fn len(&self) -> usize {
520        self.reader.len(&self.events)
521    }
522
523    /// Returns `true` if there are no events available to read.
524    ///
525    /// # Example
526    ///
527    /// The following example shows a useful pattern where some behavior is triggered if new events are available.
528    /// [`EventReader::clear()`] is used so the same events don't re-trigger the behavior the next time the system runs.
529    ///
530    /// ```
531    /// # use bevy_ecs::prelude::*;
532    /// #
533    /// #[derive(Event)]
534    /// struct CollisionEvent;
535    ///
536    /// fn play_collision_sound(mut events: EventReader<CollisionEvent>) {
537    ///     if !events.is_empty() {
538    ///         events.clear();
539    ///         // Play a sound
540    ///     }
541    /// }
542    /// # bevy_ecs::system::assert_is_system(play_collision_sound);
543    /// ```
544    pub fn is_empty(&self) -> bool {
545        self.reader.is_empty(&self.events)
546    }
547
548    /// Consumes all available events.
549    ///
550    /// This means these events will not appear in calls to [`EventReader::read()`] or
551    /// [`EventReader::read_with_id()`] and [`EventReader::is_empty()`] will return `true`.
552    ///
553    /// For usage, see [`EventReader::is_empty()`].
554    pub fn clear(&mut self) {
555        self.reader.clear(&self.events);
556    }
557}
558
559/// Sends events of type `T`.
560///
561/// # Usage
562///
563/// `EventWriter`s are usually declared as a [`SystemParam`].
564/// ```
565/// # use bevy_ecs::prelude::*;
566///
567/// #[derive(Event)]
568/// pub struct MyEvent; // Custom event type.
569/// fn my_system(mut writer: EventWriter<MyEvent>) {
570///     writer.send(MyEvent);
571/// }
572///
573/// # bevy_ecs::system::assert_is_system(my_system);
574/// ```
575/// # Observers
576///
577/// "Buffered" Events, such as those sent directly in [`Events`] or sent using [`EventWriter`], do _not_ automatically
578/// trigger any [`Observer`]s watching for that event, as each [`Event`] has different requirements regarding _if_ it will
579/// be triggered, and if so, _when_ it will be triggered in the schedule.
580///
581/// # Concurrency
582///
583/// `EventWriter` param has [`ResMut<Events<T>>`](Events) inside. So two systems declaring `EventWriter<T>` params
584/// for the same event type won't be executed concurrently.
585///
586/// # Untyped events
587///
588/// `EventWriter` can only send events of one specific type, which must be known at compile-time.
589/// This is not a problem most of the time, but you may find a situation where you cannot know
590/// ahead of time every kind of event you'll need to send. In this case, you can use the "type-erased event" pattern.
591///
592/// ```
593/// # use bevy_ecs::{prelude::*, event::Events};
594/// # #[derive(Event)]
595/// # pub struct MyEvent;
596/// fn send_untyped(mut commands: Commands) {
597///     // Send an event of a specific type without having to declare that
598///     // type as a SystemParam.
599///     //
600///     // Effectively, we're just moving the type parameter from the /type/ to the /method/,
601///     // which allows one to do all kinds of clever things with type erasure, such as sending
602///     // custom events to unknown 3rd party plugins (modding API).
603///     //
604///     // NOTE: the event won't actually be sent until commands get applied during
605///     // apply_deferred.
606///     commands.add(|w: &mut World| {
607///         w.send_event(MyEvent);
608///     });
609/// }
610/// ```
611/// Note that this is considered *non-idiomatic*, and should only be used when `EventWriter` will not work.
612///
613/// [`Observer`]: crate::observer::Observer
614#[derive(SystemParam)]
615pub struct EventWriter<'w, E: Event> {
616    events: ResMut<'w, Events<E>>,
617}
618
619impl<'w, E: Event> EventWriter<'w, E> {
620    /// Sends an `event`, which can later be read by [`EventReader`]s.
621    /// This method returns the [ID](`EventId`) of the sent `event`.
622    ///
623    /// See [`Events`] for details.
624    pub fn send(&mut self, event: E) -> EventId<E> {
625        self.events.send(event)
626    }
627
628    /// Sends a list of `events` all at once, which can later be read by [`EventReader`]s.
629    /// This is more efficient than sending each event individually.
630    /// This method returns the [IDs](`EventId`) of the sent `events`.
631    ///
632    /// See [`Events`] for details.
633    pub fn send_batch(&mut self, events: impl IntoIterator<Item = E>) -> SendBatchIds<E> {
634        self.events.send_batch(events)
635    }
636
637    /// Sends the default value of the event. Useful when the event is an empty struct.
638    /// This method returns the [ID](`EventId`) of the sent `event`.
639    ///
640    /// See [`Events`] for details.
641    pub fn send_default(&mut self) -> EventId<E>
642    where
643        E: Default,
644    {
645        self.events.send_default()
646    }
647}
648
649/// Stores the state for an [`EventReader`].
650///
651/// Access to the [`Events<E>`] resource is required to read any incoming events.
652///
653/// In almost all cases, you should just use an [`EventReader`],
654/// which will automatically manage the state for you.
655///
656/// However, this type can be useful if you need to manually track events,
657/// such as when you're attempting to send and receive events of the same type in the same system.
658///
659/// # Example
660///
661/// ```
662/// use bevy_ecs::prelude::*;
663/// use bevy_ecs::event::{Event, Events, ManualEventReader};
664///
665/// #[derive(Event, Clone, Debug)]
666/// struct MyEvent;
667///
668/// /// A system that both sends and receives events using a [`Local`] [`ManualEventReader`].
669/// fn send_and_receive_manual_event_reader(
670///     // The `Local` `SystemParam` stores state inside the system itself, rather than in the world.
671///     // `ManualEventReader<T>` is the internal state of `EventReader<T>`, which tracks which events have been seen.
672///     mut local_event_reader: Local<ManualEventReader<MyEvent>>,
673///     // We can access the `Events` resource mutably, allowing us to both read and write its contents.
674///     mut events: ResMut<Events<MyEvent>>,
675/// ) {
676///     // We must collect the events to resend, because we can't mutate events while we're iterating over the events.
677///     let mut events_to_resend = Vec::new();
678///
679///     for event in local_event_reader.read(&events) {
680///          events_to_resend.push(event.clone());
681///     }
682///
683///     for event in events_to_resend {
684///         events.send(MyEvent);
685///     }
686/// }
687///
688/// # bevy_ecs::system::assert_is_system(send_and_receive_manual_event_reader);
689/// ```
690#[derive(Debug)]
691pub struct ManualEventReader<E: Event> {
692    last_event_count: usize,
693    _marker: PhantomData<E>,
694}
695
696impl<E: Event> Default for ManualEventReader<E> {
697    fn default() -> Self {
698        ManualEventReader {
699            last_event_count: 0,
700            _marker: Default::default(),
701        }
702    }
703}
704
705impl<E: Event> Clone for ManualEventReader<E> {
706    fn clone(&self) -> Self {
707        ManualEventReader {
708            last_event_count: self.last_event_count,
709            _marker: PhantomData,
710        }
711    }
712}
713
714#[allow(clippy::len_without_is_empty)] // Check fails since the is_empty implementation has a signature other than `(&self) -> bool`
715impl<E: Event> ManualEventReader<E> {
716    /// See [`EventReader::read`]
717    pub fn read<'a>(&'a mut self, events: &'a Events<E>) -> EventIterator<'a, E> {
718        self.read_with_id(events).without_id()
719    }
720
721    /// See [`EventReader::read_with_id`]
722    pub fn read_with_id<'a>(&'a mut self, events: &'a Events<E>) -> EventIteratorWithId<'a, E> {
723        EventIteratorWithId::new(self, events)
724    }
725
726    /// See [`EventReader::par_read`]
727    #[cfg(feature = "multi_threaded")]
728    pub fn par_read<'a>(&'a mut self, events: &'a Events<E>) -> EventParIter<'a, E> {
729        EventParIter::new(self, events)
730    }
731
732    /// See [`EventReader::len`]
733    pub fn len(&self, events: &Events<E>) -> usize {
734        // The number of events in this reader is the difference between the most recent event
735        // and the last event seen by it. This will be at most the number of events contained
736        // with the events (any others have already been dropped)
737        // TODO: Warn when there are dropped events, or return e.g. a `Result<usize, (usize, usize)>`
738        events
739            .event_count
740            .saturating_sub(self.last_event_count)
741            .min(events.len())
742    }
743
744    /// Amount of events we missed.
745    pub fn missed_events(&self, events: &Events<E>) -> usize {
746        events
747            .oldest_event_count()
748            .saturating_sub(self.last_event_count)
749    }
750
751    /// See [`EventReader::is_empty()`]
752    pub fn is_empty(&self, events: &Events<E>) -> bool {
753        self.len(events) == 0
754    }
755
756    /// See [`EventReader::clear()`]
757    pub fn clear(&mut self, events: &Events<E>) {
758        self.last_event_count = events.event_count;
759    }
760}
761
762/// An iterator that yields any unread events from an [`EventReader`] or [`ManualEventReader`].
763#[derive(Debug)]
764pub struct EventIterator<'a, E: Event> {
765    iter: EventIteratorWithId<'a, E>,
766}
767
768impl<'a, E: Event> Iterator for EventIterator<'a, E> {
769    type Item = &'a E;
770    fn next(&mut self) -> Option<Self::Item> {
771        self.iter.next().map(|(event, _)| event)
772    }
773
774    fn size_hint(&self) -> (usize, Option<usize>) {
775        self.iter.size_hint()
776    }
777
778    fn count(self) -> usize {
779        self.iter.count()
780    }
781
782    fn last(self) -> Option<Self::Item>
783    where
784        Self: Sized,
785    {
786        self.iter.last().map(|(event, _)| event)
787    }
788
789    fn nth(&mut self, n: usize) -> Option<Self::Item> {
790        self.iter.nth(n).map(|(event, _)| event)
791    }
792}
793
794impl<'a, E: Event> ExactSizeIterator for EventIterator<'a, E> {
795    fn len(&self) -> usize {
796        self.iter.len()
797    }
798}
799
800/// An iterator that yields any unread events (and their IDs) from an [`EventReader`] or [`ManualEventReader`].
801#[derive(Debug)]
802pub struct EventIteratorWithId<'a, E: Event> {
803    reader: &'a mut ManualEventReader<E>,
804    chain: Chain<Iter<'a, EventInstance<E>>, Iter<'a, EventInstance<E>>>,
805    unread: usize,
806}
807
808impl<'a, E: Event> EventIteratorWithId<'a, E> {
809    /// Creates a new iterator that yields any `events` that have not yet been seen by `reader`.
810    pub fn new(reader: &'a mut ManualEventReader<E>, events: &'a Events<E>) -> Self {
811        let a_index = reader
812            .last_event_count
813            .saturating_sub(events.events_a.start_event_count);
814        let b_index = reader
815            .last_event_count
816            .saturating_sub(events.events_b.start_event_count);
817        let a = events.events_a.get(a_index..).unwrap_or_default();
818        let b = events.events_b.get(b_index..).unwrap_or_default();
819
820        let unread_count = a.len() + b.len();
821        // Ensure `len` is implemented correctly
822        debug_assert_eq!(unread_count, reader.len(events));
823        reader.last_event_count = events.event_count - unread_count;
824        // Iterate the oldest first, then the newer events
825        let chain = a.iter().chain(b.iter());
826
827        Self {
828            reader,
829            chain,
830            unread: unread_count,
831        }
832    }
833
834    /// Iterate over only the events.
835    pub fn without_id(self) -> EventIterator<'a, E> {
836        EventIterator { iter: self }
837    }
838}
839
840impl<'a, E: Event> Iterator for EventIteratorWithId<'a, E> {
841    type Item = (&'a E, EventId<E>);
842    fn next(&mut self) -> Option<Self::Item> {
843        match self
844            .chain
845            .next()
846            .map(|instance| (&instance.event, instance.event_id))
847        {
848            Some(item) => {
849                detailed_trace!("EventReader::iter() -> {}", item.1);
850                self.reader.last_event_count += 1;
851                self.unread -= 1;
852                Some(item)
853            }
854            None => None,
855        }
856    }
857
858    fn size_hint(&self) -> (usize, Option<usize>) {
859        self.chain.size_hint()
860    }
861
862    fn count(self) -> usize {
863        self.reader.last_event_count += self.unread;
864        self.unread
865    }
866
867    fn last(self) -> Option<Self::Item>
868    where
869        Self: Sized,
870    {
871        let EventInstance { event_id, event } = self.chain.last()?;
872        self.reader.last_event_count += self.unread;
873        Some((event, *event_id))
874    }
875
876    fn nth(&mut self, n: usize) -> Option<Self::Item> {
877        if let Some(EventInstance { event_id, event }) = self.chain.nth(n) {
878            self.reader.last_event_count += n + 1;
879            self.unread -= n + 1;
880            Some((event, *event_id))
881        } else {
882            self.reader.last_event_count += self.unread;
883            self.unread = 0;
884            None
885        }
886    }
887}
888
889impl<'a, E: Event> ExactSizeIterator for EventIteratorWithId<'a, E> {
890    fn len(&self) -> usize {
891        self.unread
892    }
893}
894
895/// A parallel iterator over `Event`s.
896#[cfg(feature = "multi_threaded")]
897#[derive(Debug)]
898pub struct EventParIter<'a, E: Event> {
899    reader: &'a mut ManualEventReader<E>,
900    slices: [&'a [EventInstance<E>]; 2],
901    batching_strategy: BatchingStrategy,
902    unread: usize,
903}
904
905#[cfg(feature = "multi_threaded")]
906impl<'a, E: Event> EventParIter<'a, E> {
907    /// Creates a new parallel iterator over `events` that have not yet been seen by `reader`.
908    pub fn new(reader: &'a mut ManualEventReader<E>, events: &'a Events<E>) -> Self {
909        let a_index = reader
910            .last_event_count
911            .saturating_sub(events.events_a.start_event_count);
912        let b_index = reader
913            .last_event_count
914            .saturating_sub(events.events_b.start_event_count);
915        let a = events.events_a.get(a_index..).unwrap_or_default();
916        let b = events.events_b.get(b_index..).unwrap_or_default();
917
918        let unread_count = a.len() + b.len();
919        // Ensure `len` is implemented correctly
920        debug_assert_eq!(unread_count, reader.len(events));
921        reader.last_event_count = events.event_count - unread_count;
922
923        Self {
924            reader,
925            slices: [a, b],
926            batching_strategy: BatchingStrategy::default(),
927            unread: unread_count,
928        }
929    }
930
931    /// Changes the batching strategy used when iterating.
932    ///
933    /// For more information on how this affects the resultant iteration, see
934    /// [`BatchingStrategy`].
935    pub fn batching_strategy(mut self, strategy: BatchingStrategy) -> Self {
936        self.batching_strategy = strategy;
937        self
938    }
939
940    /// Runs the provided closure for each unread event in parallel.
941    ///
942    /// Unlike normal iteration, the event order is not guaranteed in any form.
943    ///
944    /// # Panics
945    /// If the [`ComputeTaskPool`] is not initialized. If using this from an event reader that is being
946    /// initialized and run from the ECS scheduler, this should never panic.
947    ///
948    /// [`ComputeTaskPool`]: bevy_tasks::ComputeTaskPool
949    pub fn for_each<FN: Fn(&'a E) + Send + Sync + Clone>(self, func: FN) {
950        self.for_each_with_id(move |e, _| func(e));
951    }
952
953    /// Runs the provided closure for each unread event in parallel, like [`for_each`](Self::for_each),
954    /// but additionally provides the `EventId` to the closure.
955    ///
956    /// Note that the order of iteration is not guaranteed, but `EventId`s are ordered by send order.
957    ///
958    /// # Panics
959    /// If the [`ComputeTaskPool`] is not initialized. If using this from an event reader that is being
960    /// initialized and run from the ECS scheduler, this should never panic.
961    ///
962    /// [`ComputeTaskPool`]: bevy_tasks::ComputeTaskPool
963    pub fn for_each_with_id<FN: Fn(&'a E, EventId<E>) + Send + Sync + Clone>(mut self, func: FN) {
964        #[cfg(any(target_arch = "wasm32", not(feature = "multi_threaded")))]
965        {
966            self.into_iter().for_each(|(e, i)| func(e, i));
967        }
968
969        #[cfg(all(not(target_arch = "wasm32"), feature = "multi_threaded"))]
970        {
971            let pool = bevy_tasks::ComputeTaskPool::get();
972            let thread_count = pool.thread_num();
973            if thread_count <= 1 {
974                return self.into_iter().for_each(|(e, i)| func(e, i));
975            }
976
977            let batch_size = self
978                .batching_strategy
979                .calc_batch_size(|| self.len(), thread_count);
980            let chunks = self.slices.map(|s| s.chunks_exact(batch_size));
981            let remainders = chunks.each_ref().map(|c| c.remainder());
982
983            pool.scope(|scope| {
984                for batch in chunks.into_iter().flatten().chain(remainders) {
985                    let func = func.clone();
986                    scope.spawn(async move {
987                        for event in batch {
988                            func(&event.event, event.event_id);
989                        }
990                    });
991                }
992            });
993
994            // Events are guaranteed to be read at this point.
995            self.reader.last_event_count += self.unread;
996            self.unread = 0;
997        }
998    }
999
1000    /// Returns the number of [`Event`]s to be iterated.
1001    pub fn len(&self) -> usize {
1002        self.slices.iter().map(|s| s.len()).sum()
1003    }
1004
1005    /// Returns [`true`] if there are no events remaining in this iterator.
1006    pub fn is_empty(&self) -> bool {
1007        self.slices.iter().all(|x| x.is_empty())
1008    }
1009}
1010
1011#[cfg(feature = "multi_threaded")]
1012impl<'a, E: Event> IntoIterator for EventParIter<'a, E> {
1013    type IntoIter = EventIteratorWithId<'a, E>;
1014    type Item = <Self::IntoIter as Iterator>::Item;
1015
1016    fn into_iter(self) -> Self::IntoIter {
1017        let EventParIter {
1018            reader,
1019            slices: [a, b],
1020            ..
1021        } = self;
1022        let unread = a.len() + b.len();
1023        let chain = a.iter().chain(b);
1024        EventIteratorWithId {
1025            reader,
1026            chain,
1027            unread,
1028        }
1029    }
1030}
1031
1032#[doc(hidden)]
1033struct RegisteredEvent {
1034    component_id: ComponentId,
1035    // Required to flush the secondary buffer and drop events even if left unchanged.
1036    previously_updated: bool,
1037    // SAFETY: The component ID and the function must be used to fetch the Events<T> resource
1038    // of the same type initialized in `register_event`, or improper type casts will occur.
1039    update: unsafe fn(MutUntyped),
1040}
1041
1042/// A registry of all of the [`Events`] in the [`World`], used by [`event_update_system`]
1043/// to update all of the events.
1044#[derive(Resource, Default)]
1045pub struct EventRegistry {
1046    /// Should the events be updated?
1047    ///
1048    /// This field is generally automatically updated by the [`signal_event_update_system`](crate::event::update::signal_event_update_system).
1049    pub should_update: ShouldUpdateEvents,
1050    event_updates: Vec<RegisteredEvent>,
1051}
1052
1053/// Controls whether or not the events in an [`EventRegistry`] should be updated.
1054#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
1055pub enum ShouldUpdateEvents {
1056    /// Without any fixed timestep, events should always be updated each frame.
1057    #[default]
1058    Always,
1059    /// We need to wait until at least one pass of the fixed update schedules to update the events.
1060    Waiting,
1061    /// At least one pass of the fixed update schedules has occurred, and the events are ready to be updated.
1062    Ready,
1063}
1064
1065impl EventRegistry {
1066    /// Registers an event type to be updated in a given [`World`]
1067    ///
1068    /// If no instance of the [`EventRegistry`] exists in the world, this will add one - otherwise it will use
1069    /// the existing instance.
1070    pub fn register_event<T: Event>(world: &mut World) {
1071        // By initializing the resource here, we can be sure that it is present,
1072        // and receive the correct, up-to-date `ComponentId` even if it was previously removed.
1073        let component_id = world.init_resource::<Events<T>>();
1074        let mut registry = world.get_resource_or_insert_with(Self::default);
1075        registry.event_updates.push(RegisteredEvent {
1076            component_id,
1077            previously_updated: false,
1078            update: |ptr| {
1079                // SAFETY: The resource was initialized with the type Events<T>.
1080                unsafe { ptr.with_type::<Events<T>>() }
1081                    .bypass_change_detection()
1082                    .update();
1083            },
1084        });
1085    }
1086
1087    /// Removes an event from the world and it's associated [`EventRegistry`].
1088    pub fn deregister_events<T: Event>(world: &mut World) {
1089        let component_id = world.init_resource::<Events<T>>();
1090        let mut registry = world.get_resource_or_insert_with(Self::default);
1091        registry
1092            .event_updates
1093            .retain(|e| e.component_id != component_id);
1094        world.remove_resource::<Events<T>>();
1095    }
1096
1097    /// Updates all of the registered events in the World.
1098    pub fn run_updates(&mut self, world: &mut World, last_change_tick: Tick) {
1099        for registered_event in &mut self.event_updates {
1100            // Bypass the type ID -> Component ID lookup with the cached component ID.
1101            if let Some(events) = world.get_resource_mut_by_id(registered_event.component_id) {
1102                let has_changed = events.has_changed_since(last_change_tick);
1103                if registered_event.previously_updated || has_changed {
1104                    // SAFETY: The update function pointer is called with the resource
1105                    // fetched from the same component ID.
1106                    unsafe { (registered_event.update)(events) };
1107                    // Always set to true if the events have changed, otherwise disable running on the second invocation
1108                    // to wait for more changes.
1109                    registered_event.previously_updated =
1110                        has_changed || !registered_event.previously_updated;
1111                }
1112            }
1113        }
1114    }
1115}
1116
1117#[doc(hidden)]
1118#[derive(SystemSet, Clone, Debug, PartialEq, Eq, Hash)]
1119pub struct EventUpdates;
1120
1121/// Signals the [`event_update_system`] to run after `FixedUpdate` systems.
1122///
1123/// This will change the behavior of the [`EventRegistry`] to only run after a fixed update cycle has passed.
1124/// Normally, this will simply run every frame.
1125pub fn signal_event_update_system(signal: Option<ResMut<EventRegistry>>) {
1126    if let Some(mut registry) = signal {
1127        registry.should_update = ShouldUpdateEvents::Ready;
1128    }
1129}
1130
1131/// A system that calls [`Events::update`] on all registered [`Events`] in the world.
1132pub fn event_update_system(world: &mut World, mut last_change_tick: Local<Tick>) {
1133    if world.contains_resource::<EventRegistry>() {
1134        world.resource_scope(|world, mut registry: Mut<EventRegistry>| {
1135            registry.run_updates(world, *last_change_tick);
1136
1137            registry.should_update = match registry.should_update {
1138                // If we're always updating, keep doing so.
1139                ShouldUpdateEvents::Always => ShouldUpdateEvents::Always,
1140                // Disable the system until signal_event_update_system runs again.
1141                ShouldUpdateEvents::Waiting | ShouldUpdateEvents::Ready => {
1142                    ShouldUpdateEvents::Waiting
1143                }
1144            };
1145        });
1146    }
1147    *last_change_tick = world.change_tick();
1148}
1149
1150/// A run condition for [`event_update_system`].
1151///
1152/// If [`signal_event_update_system`] has been run at least once,
1153/// we will wait for it to be run again before updating the events.
1154///
1155/// Otherwise, we will always update the events.
1156pub fn event_update_condition(maybe_signal: Option<Res<EventRegistry>>) -> bool {
1157    match maybe_signal {
1158        Some(signal) => match signal.should_update {
1159            ShouldUpdateEvents::Always | ShouldUpdateEvents::Ready => true,
1160            ShouldUpdateEvents::Waiting => false,
1161        },
1162        None => true,
1163    }
1164}
1165
1166/// [`Iterator`] over sent [`EventIds`](`EventId`) from a batch.
1167pub struct SendBatchIds<E> {
1168    last_count: usize,
1169    event_count: usize,
1170    _marker: PhantomData<E>,
1171}
1172
1173impl<E: Event> Iterator for SendBatchIds<E> {
1174    type Item = EventId<E>;
1175
1176    fn next(&mut self) -> Option<Self::Item> {
1177        if self.last_count >= self.event_count {
1178            return None;
1179        }
1180
1181        let result = Some(EventId {
1182            id: self.last_count,
1183            _marker: PhantomData,
1184        });
1185
1186        self.last_count += 1;
1187
1188        result
1189    }
1190}
1191
1192impl<E: Event> ExactSizeIterator for SendBatchIds<E> {
1193    fn len(&self) -> usize {
1194        self.event_count.saturating_sub(self.last_count)
1195    }
1196}
1197
1198#[cfg(test)]
1199mod tests {
1200    use crate::system::assert_is_read_only_system;
1201
1202    use super::*;
1203
1204    #[derive(Event, Copy, Clone, PartialEq, Eq, Debug)]
1205    struct TestEvent {
1206        i: usize,
1207    }
1208
1209    #[test]
1210    fn test_events() {
1211        let mut events = Events::<TestEvent>::default();
1212        let event_0 = TestEvent { i: 0 };
1213        let event_1 = TestEvent { i: 1 };
1214        let event_2 = TestEvent { i: 2 };
1215
1216        // this reader will miss event_0 and event_1 because it wont read them over the course of
1217        // two updates
1218        let mut reader_missed = events.get_reader();
1219
1220        let mut reader_a = events.get_reader();
1221
1222        events.send(event_0);
1223
1224        assert_eq!(
1225            get_events(&events, &mut reader_a),
1226            vec![event_0],
1227            "reader_a created before event receives event"
1228        );
1229        assert_eq!(
1230            get_events(&events, &mut reader_a),
1231            vec![],
1232            "second iteration of reader_a created before event results in zero events"
1233        );
1234
1235        let mut reader_b = events.get_reader();
1236
1237        assert_eq!(
1238            get_events(&events, &mut reader_b),
1239            vec![event_0],
1240            "reader_b created after event receives event"
1241        );
1242        assert_eq!(
1243            get_events(&events, &mut reader_b),
1244            vec![],
1245            "second iteration of reader_b created after event results in zero events"
1246        );
1247
1248        events.send(event_1);
1249
1250        let mut reader_c = events.get_reader();
1251
1252        assert_eq!(
1253            get_events(&events, &mut reader_c),
1254            vec![event_0, event_1],
1255            "reader_c created after two events receives both events"
1256        );
1257        assert_eq!(
1258            get_events(&events, &mut reader_c),
1259            vec![],
1260            "second iteration of reader_c created after two event results in zero events"
1261        );
1262
1263        assert_eq!(
1264            get_events(&events, &mut reader_a),
1265            vec![event_1],
1266            "reader_a receives next unread event"
1267        );
1268
1269        events.update();
1270
1271        let mut reader_d = events.get_reader();
1272
1273        events.send(event_2);
1274
1275        assert_eq!(
1276            get_events(&events, &mut reader_a),
1277            vec![event_2],
1278            "reader_a receives event created after update"
1279        );
1280        assert_eq!(
1281            get_events(&events, &mut reader_b),
1282            vec![event_1, event_2],
1283            "reader_b receives events created before and after update"
1284        );
1285        assert_eq!(
1286            get_events(&events, &mut reader_d),
1287            vec![event_0, event_1, event_2],
1288            "reader_d receives all events created before and after update"
1289        );
1290
1291        events.update();
1292
1293        assert_eq!(
1294            get_events(&events, &mut reader_missed),
1295            vec![event_2],
1296            "reader_missed missed events unread after two update() calls"
1297        );
1298    }
1299
1300    fn get_events<E: Event + Clone>(
1301        events: &Events<E>,
1302        reader: &mut ManualEventReader<E>,
1303    ) -> Vec<E> {
1304        reader.read(events).cloned().collect::<Vec<E>>()
1305    }
1306
1307    #[derive(Event, PartialEq, Eq, Debug)]
1308    struct E(usize);
1309
1310    fn events_clear_and_read_impl(clear_func: impl FnOnce(&mut Events<E>)) {
1311        let mut events = Events::<E>::default();
1312        let mut reader = events.get_reader();
1313
1314        assert!(reader.read(&events).next().is_none());
1315
1316        events.send(E(0));
1317        assert_eq!(*reader.read(&events).next().unwrap(), E(0));
1318        assert_eq!(reader.read(&events).next(), None);
1319
1320        events.send(E(1));
1321        clear_func(&mut events);
1322        assert!(reader.read(&events).next().is_none());
1323
1324        events.send(E(2));
1325        events.update();
1326        events.send(E(3));
1327
1328        assert!(reader.read(&events).eq([E(2), E(3)].iter()));
1329    }
1330
1331    #[test]
1332    fn test_events_clear_and_read() {
1333        events_clear_and_read_impl(|events| events.clear());
1334    }
1335
1336    #[test]
1337    fn test_events_drain_and_read() {
1338        events_clear_and_read_impl(|events| {
1339            assert!(events.drain().eq(vec![E(0), E(1)].into_iter()));
1340        });
1341    }
1342
1343    #[test]
1344    fn test_events_extend_impl() {
1345        let mut events = Events::<TestEvent>::default();
1346        let mut reader = events.get_reader();
1347
1348        events.extend(vec![TestEvent { i: 0 }, TestEvent { i: 1 }]);
1349        assert!(reader
1350            .read(&events)
1351            .eq([TestEvent { i: 0 }, TestEvent { i: 1 }].iter()));
1352    }
1353
1354    #[test]
1355    fn test_events_empty() {
1356        let mut events = Events::<TestEvent>::default();
1357        assert!(events.is_empty());
1358
1359        events.send(TestEvent { i: 0 });
1360        assert!(!events.is_empty());
1361
1362        events.update();
1363        assert!(!events.is_empty());
1364
1365        // events are only empty after the second call to update
1366        // due to double buffering.
1367        events.update();
1368        assert!(events.is_empty());
1369    }
1370
1371    #[test]
1372    fn test_event_reader_len_empty() {
1373        let events = Events::<TestEvent>::default();
1374        assert_eq!(events.get_reader().len(&events), 0);
1375        assert!(events.get_reader().is_empty(&events));
1376    }
1377
1378    #[test]
1379    fn test_event_reader_len_filled() {
1380        let mut events = Events::<TestEvent>::default();
1381        events.send(TestEvent { i: 0 });
1382        assert_eq!(events.get_reader().len(&events), 1);
1383        assert!(!events.get_reader().is_empty(&events));
1384    }
1385
1386    #[test]
1387    fn test_event_iter_len_updated() {
1388        let mut events = Events::<TestEvent>::default();
1389        events.send(TestEvent { i: 0 });
1390        events.send(TestEvent { i: 1 });
1391        events.send(TestEvent { i: 2 });
1392        let mut reader = events.get_reader();
1393        let mut iter = reader.read(&events);
1394        assert_eq!(iter.len(), 3);
1395        iter.next();
1396        assert_eq!(iter.len(), 2);
1397        iter.next();
1398        assert_eq!(iter.len(), 1);
1399        iter.next();
1400        assert_eq!(iter.len(), 0);
1401    }
1402
1403    #[test]
1404    fn test_event_reader_len_current() {
1405        let mut events = Events::<TestEvent>::default();
1406        events.send(TestEvent { i: 0 });
1407        let reader = events.get_reader_current();
1408        dbg!(&reader);
1409        dbg!(&events);
1410        assert!(reader.is_empty(&events));
1411        events.send(TestEvent { i: 0 });
1412        assert_eq!(reader.len(&events), 1);
1413        assert!(!reader.is_empty(&events));
1414    }
1415
1416    #[test]
1417    fn test_event_reader_len_update() {
1418        let mut events = Events::<TestEvent>::default();
1419        events.send(TestEvent { i: 0 });
1420        events.send(TestEvent { i: 0 });
1421        let reader = events.get_reader();
1422        assert_eq!(reader.len(&events), 2);
1423        events.update();
1424        events.send(TestEvent { i: 0 });
1425        assert_eq!(reader.len(&events), 3);
1426        events.update();
1427        assert_eq!(reader.len(&events), 1);
1428        events.update();
1429        assert!(reader.is_empty(&events));
1430    }
1431
1432    #[test]
1433    fn test_event_reader_clear() {
1434        use bevy_ecs::prelude::*;
1435
1436        let mut world = World::new();
1437        let mut events = Events::<TestEvent>::default();
1438        events.send(TestEvent { i: 0 });
1439        world.insert_resource(events);
1440
1441        let mut reader = IntoSystem::into_system(|mut events: EventReader<TestEvent>| -> bool {
1442            if !events.is_empty() {
1443                events.clear();
1444                false
1445            } else {
1446                true
1447            }
1448        });
1449        reader.initialize(&mut world);
1450
1451        let is_empty = reader.run((), &mut world);
1452        assert!(!is_empty, "EventReader should not be empty");
1453        let is_empty = reader.run((), &mut world);
1454        assert!(is_empty, "EventReader should be empty");
1455    }
1456
1457    #[test]
1458    fn test_update_drain() {
1459        let mut events = Events::<TestEvent>::default();
1460        let mut reader = events.get_reader();
1461
1462        events.send(TestEvent { i: 0 });
1463        events.send(TestEvent { i: 1 });
1464        assert_eq!(reader.read(&events).count(), 2);
1465
1466        let mut old_events = Vec::from_iter(events.update_drain());
1467        assert!(old_events.is_empty());
1468
1469        events.send(TestEvent { i: 2 });
1470        assert_eq!(reader.read(&events).count(), 1);
1471
1472        old_events.extend(events.update_drain());
1473        assert_eq!(old_events.len(), 2);
1474
1475        old_events.extend(events.update_drain());
1476        assert_eq!(
1477            old_events,
1478            &[TestEvent { i: 0 }, TestEvent { i: 1 }, TestEvent { i: 2 }]
1479        );
1480    }
1481
1482    #[allow(clippy::iter_nth_zero)]
1483    #[test]
1484    fn test_event_iter_nth() {
1485        use bevy_ecs::prelude::*;
1486
1487        let mut world = World::new();
1488        world.init_resource::<Events<TestEvent>>();
1489
1490        world.send_event(TestEvent { i: 0 });
1491        world.send_event(TestEvent { i: 1 });
1492        world.send_event(TestEvent { i: 2 });
1493        world.send_event(TestEvent { i: 3 });
1494        world.send_event(TestEvent { i: 4 });
1495
1496        let mut schedule = Schedule::default();
1497        schedule.add_systems(|mut events: EventReader<TestEvent>| {
1498            let mut iter = events.read();
1499
1500            assert_eq!(iter.next(), Some(&TestEvent { i: 0 }));
1501            assert_eq!(iter.nth(2), Some(&TestEvent { i: 3 }));
1502            assert_eq!(iter.nth(1), None);
1503
1504            assert!(events.is_empty());
1505        });
1506        schedule.run(&mut world);
1507    }
1508
1509    #[test]
1510    fn test_event_iter_last() {
1511        use bevy_ecs::prelude::*;
1512
1513        let mut world = World::new();
1514        world.init_resource::<Events<TestEvent>>();
1515
1516        let mut reader =
1517            IntoSystem::into_system(|mut events: EventReader<TestEvent>| -> Option<TestEvent> {
1518                events.read().last().copied()
1519            });
1520        reader.initialize(&mut world);
1521
1522        let last = reader.run((), &mut world);
1523        assert!(last.is_none(), "EventReader should be empty");
1524
1525        world.send_event(TestEvent { i: 0 });
1526        let last = reader.run((), &mut world);
1527        assert_eq!(last, Some(TestEvent { i: 0 }));
1528
1529        world.send_event(TestEvent { i: 1 });
1530        world.send_event(TestEvent { i: 2 });
1531        world.send_event(TestEvent { i: 3 });
1532        let last = reader.run((), &mut world);
1533        assert_eq!(last, Some(TestEvent { i: 3 }));
1534
1535        let last = reader.run((), &mut world);
1536        assert!(last.is_none(), "EventReader should be empty");
1537    }
1538
1539    #[derive(Event, Clone, PartialEq, Debug, Default)]
1540    struct EmptyTestEvent;
1541
1542    #[test]
1543    fn test_firing_empty_event() {
1544        let mut events = Events::<EmptyTestEvent>::default();
1545        events.send_default();
1546
1547        let mut reader = events.get_reader();
1548        assert_eq!(get_events(&events, &mut reader), vec![EmptyTestEvent]);
1549    }
1550
1551    #[test]
1552    fn ensure_reader_readonly() {
1553        fn reader_system(_: EventReader<EmptyTestEvent>) {}
1554
1555        assert_is_read_only_system(reader_system);
1556    }
1557
1558    #[test]
1559    fn test_send_events_ids() {
1560        let mut events = Events::<TestEvent>::default();
1561        let event_0 = TestEvent { i: 0 };
1562        let event_1 = TestEvent { i: 1 };
1563        let event_2 = TestEvent { i: 2 };
1564
1565        let event_0_id = events.send(event_0);
1566
1567        assert_eq!(
1568            events.get_event(event_0_id.id),
1569            Some((&event_0, event_0_id)),
1570            "Getting a sent event by ID should return the original event"
1571        );
1572
1573        let mut event_ids = events.send_batch([event_1, event_2]);
1574
1575        let event_id = event_ids.next().expect("Event 1 must have been sent");
1576
1577        assert_eq!(
1578            events.get_event(event_id.id),
1579            Some((&event_1, event_id)),
1580            "Getting a sent event by ID should return the original event"
1581        );
1582
1583        let event_id = event_ids.next().expect("Event 2 must have been sent");
1584
1585        assert_eq!(
1586            events.get_event(event_id.id),
1587            Some((&event_2, event_id)),
1588            "Getting a sent event by ID should return the original event"
1589        );
1590
1591        assert!(
1592            event_ids.next().is_none(),
1593            "Only sent two events; got more than two IDs"
1594        );
1595    }
1596
1597    #[cfg(feature = "multi_threaded")]
1598    #[test]
1599    fn test_events_par_iter() {
1600        use crate::prelude::*;
1601        use std::sync::atomic::{AtomicUsize, Ordering};
1602
1603        #[derive(Resource)]
1604        struct Counter(AtomicUsize);
1605
1606        let mut world = World::new();
1607        world.init_resource::<Events<TestEvent>>();
1608        for _ in 0..100 {
1609            world.send_event(TestEvent { i: 1 });
1610        }
1611        let mut schedule = Schedule::default();
1612        schedule.add_systems(
1613            |mut events: EventReader<TestEvent>, counter: ResMut<Counter>| {
1614                events.par_read().for_each(|event| {
1615                    counter.0.fetch_add(event.i, Ordering::Relaxed);
1616                });
1617            },
1618        );
1619        world.insert_resource(Counter(AtomicUsize::new(0)));
1620        schedule.run(&mut world);
1621        let counter = world.remove_resource::<Counter>().unwrap();
1622        assert_eq!(counter.0.into_inner(), 100);
1623
1624        world.insert_resource(Counter(AtomicUsize::new(0)));
1625        schedule.run(&mut world);
1626        let counter = world.remove_resource::<Counter>().unwrap();
1627        assert_eq!(counter.0.into_inner(), 0);
1628    }
1629
1630    #[test]
1631    fn iter_current_update_events_iterates_over_current_events() {
1632        #[derive(Event, Clone)]
1633        struct TestEvent;
1634
1635        let mut test_events = Events::<TestEvent>::default();
1636
1637        // Starting empty
1638        assert_eq!(test_events.len(), 0);
1639        assert_eq!(test_events.iter_current_update_events().count(), 0);
1640        test_events.update();
1641
1642        // Sending one event
1643        test_events.send(TestEvent);
1644
1645        assert_eq!(test_events.len(), 1);
1646        assert_eq!(test_events.iter_current_update_events().count(), 1);
1647        test_events.update();
1648
1649        // Sending two events on the next frame
1650        test_events.send(TestEvent);
1651        test_events.send(TestEvent);
1652
1653        assert_eq!(test_events.len(), 3); // Events are double-buffered, so we see 1 + 2 = 3
1654        assert_eq!(test_events.iter_current_update_events().count(), 2);
1655        test_events.update();
1656
1657        // Sending zero events
1658        assert_eq!(test_events.len(), 2); // Events are double-buffered, so we see 2 + 0 = 2
1659        assert_eq!(test_events.iter_current_update_events().count(), 0);
1660    }
1661
1662    #[test]
1663    fn test_event_registry_can_add_and_remove_events_to_world() {
1664        use bevy_ecs::prelude::*;
1665
1666        let mut world = World::new();
1667        EventRegistry::register_event::<TestEvent>(&mut world);
1668
1669        let has_events = world.get_resource::<Events<TestEvent>>().is_some();
1670
1671        assert!(has_events, "Should have the events resource");
1672
1673        EventRegistry::deregister_events::<TestEvent>(&mut world);
1674
1675        let has_events = world.get_resource::<Events<TestEvent>>().is_some();
1676
1677        assert!(!has_events, "Should not have the events resource");
1678    }
1679}