2021-09-17 18:00:29 +00:00
|
|
|
//! Event handling types.
|
|
|
|
|
2022-05-09 13:19:32 +00:00
|
|
|
use crate as bevy_ecs;
|
2021-10-03 19:23:44 +00:00
|
|
|
use crate::system::{Local, Res, ResMut, SystemParam};
|
2020-11-21 22:03:18 +00:00
|
|
|
use bevy_utils::tracing::trace;
|
2022-05-10 20:18:59 +00:00
|
|
|
use std::ops::{Deref, DerefMut};
|
2021-03-10 22:37:02 +00:00
|
|
|
use std::{
|
|
|
|
fmt::{self},
|
|
|
|
hash::Hash,
|
|
|
|
marker::PhantomData,
|
|
|
|
};
|
2020-11-21 22:03:18 +00:00
|
|
|
|
2022-05-09 13:19:32 +00:00
|
|
|
/// A type that can be stored in an [`Events<E>`] resource
|
|
|
|
/// You can conveniently access events using the [`EventReader`] and [`EventWriter`] system parameter.
|
|
|
|
///
|
|
|
|
/// Events must be thread-safe.
|
|
|
|
pub trait Event: Send + Sync + 'static {}
|
|
|
|
impl<T> Event for T where T: Send + Sync + 'static {}
|
|
|
|
|
2020-11-21 22:03:18 +00:00
|
|
|
/// An `EventId` uniquely identifies an event.
|
|
|
|
///
|
|
|
|
/// An `EventId` can among other things be used to trace the flow of an event from the point it was
|
|
|
|
/// sent to the point it was processed.
|
|
|
|
#[derive(Eq, PartialEq, Ord, PartialOrd, Hash)]
|
2022-05-09 13:19:32 +00:00
|
|
|
pub struct EventId<E: Event> {
|
2020-11-21 22:03:18 +00:00
|
|
|
pub id: usize,
|
2022-05-09 13:19:32 +00:00
|
|
|
_marker: PhantomData<E>,
|
2020-11-21 22:03:18 +00:00
|
|
|
}
|
|
|
|
|
2022-05-09 13:19:32 +00:00
|
|
|
impl<E: Event> Copy for EventId<E> {}
|
|
|
|
impl<E: Event> Clone for EventId<E> {
|
2020-11-21 22:03:18 +00:00
|
|
|
fn clone(&self) -> Self {
|
|
|
|
*self
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-05-09 13:19:32 +00:00
|
|
|
impl<E: Event> fmt::Display for EventId<E> {
|
2020-11-21 22:03:18 +00:00
|
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
|
|
<Self as fmt::Debug>::fmt(self, f)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-05-09 13:19:32 +00:00
|
|
|
impl<E: Event> fmt::Debug for EventId<E> {
|
2020-11-21 22:03:18 +00:00
|
|
|
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
|
|
|
write!(
|
|
|
|
f,
|
|
|
|
"event<{}>#{}",
|
2022-05-09 13:19:32 +00:00
|
|
|
std::any::type_name::<E>().split("::").last().unwrap(),
|
2020-11-21 22:03:18 +00:00
|
|
|
self.id,
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|
2020-03-30 05:44:38 +00:00
|
|
|
|
2020-06-04 06:22:32 +00:00
|
|
|
#[derive(Debug)]
|
2022-05-09 13:19:32 +00:00
|
|
|
struct EventInstance<E: Event> {
|
|
|
|
pub event_id: EventId<E>,
|
|
|
|
pub event: E,
|
2020-03-30 05:44:38 +00:00
|
|
|
}
|
|
|
|
|
2021-03-11 00:27:30 +00:00
|
|
|
/// An event collection that represents the events that occurred within the last two
|
2021-03-17 23:42:19 +00:00
|
|
|
/// [`Events::update`] calls.
|
|
|
|
/// Events can be written to using an [`EventWriter`]
|
|
|
|
/// and are typically cheaply read using an [`EventReader`].
|
|
|
|
///
|
|
|
|
/// Each event can be consumed by multiple systems, in parallel,
|
|
|
|
/// with consumption tracked by the [`EventReader`] on a per-system basis.
|
|
|
|
///
|
2022-01-09 03:48:27 +00:00
|
|
|
/// If no [ordering](https://github.com/bevyengine/bevy/blob/main/examples/ecs/ecs_guide.rs)
|
|
|
|
/// is applied between writing and reading systems, there is a risk of a race condition.
|
|
|
|
/// This means that whether the events arrive before or after the next [`Events::update`] is unpredictable.
|
|
|
|
///
|
2021-03-17 23:42:19 +00:00
|
|
|
/// This collection is meant to be paired with a system that calls
|
|
|
|
/// [`Events::update`] exactly once per update/frame.
|
|
|
|
///
|
|
|
|
/// [`Events::update_system`] is a system that does this, typically intialized automatically using
|
2022-01-09 03:48:27 +00:00
|
|
|
/// [`add_event`](https://docs.rs/bevy/*/bevy/app/struct.App.html#method.add_event).
|
|
|
|
/// [`EventReader`]s are expected to read events from this collection at least once per loop/frame.
|
2021-03-17 23:42:19 +00:00
|
|
|
/// Events will persist across a single frame boundary and so ordering of event producers and
|
|
|
|
/// consumers is not critical (although poorly-planned ordering may cause accumulating lag).
|
|
|
|
/// If events are not handled by the end of the frame after they are updated, they will be
|
|
|
|
/// dropped silently.
|
2020-04-01 01:04:54 +00:00
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
/// ```
|
2021-04-13 20:36:37 +00:00
|
|
|
/// use bevy_ecs::event::Events;
|
2020-04-04 19:43:16 +00:00
|
|
|
///
|
2020-04-01 01:04:54 +00:00
|
|
|
/// struct MyEvent {
|
|
|
|
/// value: usize
|
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// // setup
|
|
|
|
/// let mut events = Events::<MyEvent>::default();
|
|
|
|
/// let mut reader = events.get_reader();
|
|
|
|
///
|
|
|
|
/// // run this once per update/frame
|
|
|
|
/// events.update();
|
|
|
|
///
|
|
|
|
/// // somewhere else: send an event
|
|
|
|
/// events.send(MyEvent { value: 1 });
|
|
|
|
///
|
|
|
|
/// // somewhere else: read the events
|
2020-04-28 17:59:42 +00:00
|
|
|
/// for event in reader.iter(&events) {
|
2020-04-01 01:04:54 +00:00
|
|
|
/// assert_eq!(event.value, 1)
|
|
|
|
/// }
|
|
|
|
///
|
|
|
|
/// // events are only processed once per reader
|
2020-04-28 17:59:42 +00:00
|
|
|
/// assert_eq!(reader.iter(&events).count(), 0);
|
2020-10-01 17:58:21 +00:00
|
|
|
/// ```
|
2020-04-01 01:04:54 +00:00
|
|
|
///
|
|
|
|
/// # Details
|
|
|
|
///
|
2022-01-09 03:48:27 +00:00
|
|
|
/// [`Events`] is implemented using a variation of a double buffer strategy.
|
|
|
|
/// Each call to [`update`](Events::update) swaps buffers and clears out the oldest one.
|
|
|
|
/// - [`EventReader`]s will read events from both buffers.
|
|
|
|
/// - [`EventReader`]s that read at least once per update will never drop events.
|
|
|
|
/// - [`EventReader`]s that read once within two updates might still receive some events
|
|
|
|
/// - [`EventReader`]s that read after two updates are guaranteed to drop all events that occurred
|
2021-03-11 00:27:30 +00:00
|
|
|
/// before those updates.
|
2020-04-01 01:04:54 +00:00
|
|
|
///
|
2022-01-09 03:48:27 +00:00
|
|
|
/// The buffers in [`Events`] will grow indefinitely if [`update`](Events::update) is never called.
|
2020-04-01 01:04:54 +00:00
|
|
|
///
|
2022-01-09 03:48:27 +00:00
|
|
|
/// An alternative call pattern would be to call [`update`](Events::update)
|
|
|
|
/// manually across frames to control when events are cleared.
|
2021-03-17 23:42:19 +00:00
|
|
|
/// This complicates consumption and risks ever-expanding memory usage if not cleaned up,
|
2022-01-09 03:48:27 +00:00
|
|
|
/// but can be done by adding your event as a resource instead of using
|
|
|
|
/// [`add_event`](https://docs.rs/bevy/*/bevy/app/struct.App.html#method.add_event).
|
2022-02-04 01:24:47 +00:00
|
|
|
///
|
|
|
|
/// [Example usage.](https://github.com/bevyengine/bevy/blob/latest/examples/ecs/event.rs)
|
2022-06-28 16:37:36 +00:00
|
|
|
/// [Example usage standalone.](https://github.com/bevyengine/bevy/blob/latest/crates/bevy_ecs/examples/events.rs)
|
2022-02-04 01:24:47 +00:00
|
|
|
///
|
2020-06-04 06:22:32 +00:00
|
|
|
#[derive(Debug)]
|
2022-05-09 13:19:32 +00:00
|
|
|
pub struct Events<E: Event> {
|
2022-05-10 20:18:59 +00:00
|
|
|
/// Holds the oldest still active events.
|
|
|
|
/// Note that a.start_event_count + a.len() should always === events_b.start_event_count.
|
|
|
|
events_a: EventSequence<E>,
|
|
|
|
/// Holds the newer events.
|
|
|
|
events_b: EventSequence<E>,
|
2020-03-30 05:44:38 +00:00
|
|
|
event_count: usize,
|
|
|
|
}
|
|
|
|
|
2022-05-10 20:18:59 +00:00
|
|
|
// Derived Default impl would incorrectly require E: Default
|
2022-05-09 13:19:32 +00:00
|
|
|
impl<E: Event> Default for Events<E> {
|
2020-03-30 05:44:38 +00:00
|
|
|
fn default() -> Self {
|
2022-05-10 20:18:59 +00:00
|
|
|
Self {
|
|
|
|
events_a: Default::default(),
|
|
|
|
events_b: Default::default(),
|
|
|
|
event_count: Default::default(),
|
2020-03-30 05:44:38 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-05-10 20:18:59 +00:00
|
|
|
#[derive(Debug)]
|
|
|
|
struct EventSequence<E: Event> {
|
|
|
|
events: Vec<EventInstance<E>>,
|
|
|
|
start_event_count: usize,
|
|
|
|
}
|
|
|
|
|
|
|
|
// Derived Default impl would incorrectly require E: Default
|
|
|
|
impl<E: Event> Default for EventSequence<E> {
|
|
|
|
fn default() -> Self {
|
|
|
|
Self {
|
|
|
|
events: Default::default(),
|
|
|
|
start_event_count: Default::default(),
|
|
|
|
}
|
|
|
|
}
|
2020-11-21 22:03:18 +00:00
|
|
|
}
|
|
|
|
|
2022-05-10 20:18:59 +00:00
|
|
|
impl<E: Event> Deref for EventSequence<E> {
|
|
|
|
type Target = Vec<EventInstance<E>>;
|
|
|
|
|
|
|
|
fn deref(&self) -> &Self::Target {
|
|
|
|
&self.events
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<E: Event> DerefMut for EventSequence<E> {
|
|
|
|
fn deref_mut(&mut self) -> &mut Self::Target {
|
|
|
|
&mut self.events
|
|
|
|
}
|
2020-03-30 05:44:38 +00:00
|
|
|
}
|
|
|
|
|
2020-08-16 03:27:41 +00:00
|
|
|
/// Reads events of type `T` in order and tracks which events have already been read.
|
2021-01-19 06:23:30 +00:00
|
|
|
#[derive(SystemParam)]
|
2022-05-09 13:19:32 +00:00
|
|
|
pub struct EventReader<'w, 's, E: Event> {
|
2022-05-10 20:18:59 +00:00
|
|
|
reader: Local<'s, ManualEventReader<E>>,
|
2022-05-09 13:19:32 +00:00
|
|
|
events: Res<'w, Events<E>>,
|
2021-01-19 06:23:30 +00:00
|
|
|
}
|
|
|
|
|
2022-05-10 20:18:59 +00:00
|
|
|
impl<'w, 's, E: Event> EventReader<'w, 's, E> {
|
|
|
|
/// Iterates over the events this [`EventReader`] has not seen yet. This updates the
|
|
|
|
/// [`EventReader`]'s event counter, which means subsequent event reads will not include events
|
|
|
|
/// that happened before now.
|
|
|
|
pub fn iter(&mut self) -> impl DoubleEndedIterator<Item = &E> + ExactSizeIterator<Item = &E> {
|
|
|
|
self.iter_with_id().map(|(event, _id)| event)
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Like [`iter`](Self::iter), except also returning the [`EventId`] of the events.
|
|
|
|
pub fn iter_with_id(
|
|
|
|
&mut self,
|
|
|
|
) -> impl DoubleEndedIterator<Item = (&E, EventId<E>)> + ExactSizeIterator<Item = (&E, EventId<E>)>
|
|
|
|
{
|
|
|
|
self.reader.iter_with_id(&self.events).map(|r @ (_, id)| {
|
|
|
|
trace!("EventReader::iter() -> {}", id);
|
|
|
|
r
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Determines the number of events available to be read from this [`EventReader`] without consuming any.
|
|
|
|
pub fn len(&self) -> usize {
|
|
|
|
self.reader.len(&self.events)
|
|
|
|
}
|
|
|
|
|
2022-05-13 00:57:04 +00:00
|
|
|
/// Determines if no events are available to be read without consuming any.
|
|
|
|
/// If you need to consume the iterator you can use [`EventReader::clear`].
|
|
|
|
///
|
|
|
|
/// # Example
|
|
|
|
///
|
|
|
|
/// The following example shows a common pattern of this function in conjunction with `clear`
|
|
|
|
/// to avoid leaking events to the next schedule iteration while also checking if it was emitted.
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// # use bevy_ecs::prelude::*;
|
|
|
|
/// #
|
|
|
|
/// struct CollisionEvent;
|
|
|
|
///
|
|
|
|
/// fn play_collision_sound(events: EventReader<CollisionEvent>) {
|
|
|
|
/// if !events.is_empty() {
|
|
|
|
/// events.clear();
|
|
|
|
/// // Play a sound
|
|
|
|
/// }
|
|
|
|
/// }
|
|
|
|
/// # bevy_ecs::system::assert_is_system(play_collision_sound);
|
|
|
|
/// ```
|
2022-05-10 20:18:59 +00:00
|
|
|
pub fn is_empty(&self) -> bool {
|
|
|
|
self.len() == 0
|
|
|
|
}
|
2022-05-13 00:57:04 +00:00
|
|
|
|
|
|
|
/// Consumes the iterator.
|
|
|
|
///
|
|
|
|
/// This means all currently available events will be removed before the next frame.
|
|
|
|
/// This is useful when multiple events are sent in a single frame and you want
|
|
|
|
/// to react to one or more events without needing to know how many were sent.
|
|
|
|
/// In those situations you generally want to consume those events to make sure they don't appear in the next frame.
|
|
|
|
///
|
|
|
|
/// For more information see [`EventReader::is_empty()`].
|
|
|
|
pub fn clear(mut self) {
|
|
|
|
self.iter().last();
|
|
|
|
}
|
2022-05-10 20:18:59 +00:00
|
|
|
}
|
|
|
|
|
2021-03-07 20:42:04 +00:00
|
|
|
/// Sends events of type `T`.
|
|
|
|
#[derive(SystemParam)]
|
2022-05-09 13:19:32 +00:00
|
|
|
pub struct EventWriter<'w, 's, E: Event> {
|
|
|
|
events: ResMut<'w, Events<E>>,
|
System Param Lifetime Split (#2605)
# Objective
Enable using exact World lifetimes during read-only access . This is motivated by the new renderer's need to allow read-only world-only queries to outlive the query itself (but still be constrained by the world lifetime).
For example:
https://github.com/bevyengine/bevy/blob/115b170d1f11a91146bb6d6e9684dceb8b21f786/pipelined/bevy_pbr2/src/render/mod.rs#L774
## Solution
Split out SystemParam state and world lifetimes and pipe those lifetimes up to read-only Query ops (and add into_inner for Res). According to every safety test I've run so far (except one), this is safe (see the temporary safety test commit). Note that changing the mutable variants to the new lifetimes would allow aliased mutable pointers (try doing that to see how it affects the temporary safety tests).
The new state lifetime on SystemParam does make `#[derive(SystemParam)]` more cumbersome (the current impl requires PhantomData if you don't use both lifetimes). We can make this better by detecting whether or not a lifetime is used in the derive and adjusting accordingly, but that should probably be done in its own pr.
## Why is this a draft?
The new lifetimes break QuerySet safety in one very specific case (see the query_set system in system_safety_test). We need to solve this before we can use the lifetimes given.
This is due to the fact that QuerySet is just a wrapper over Query, which now relies on world lifetimes instead of `&self` lifetimes to prevent aliasing (but in systems, each Query has its own implied lifetime, not a centralized world lifetime). I believe the fix is to rewrite QuerySet to have its own World lifetime (and own the internal reference). This will complicate the impl a bit, but I think it is doable. I'm curious if anyone else has better ideas.
Personally, I think these new lifetimes need to happen. We've gotta have a way to directly tie read-only World queries to the World lifetime. The new renderer is the first place this has come up, but I doubt it will be the last. Worst case scenario we can come up with a second `WorldLifetimeQuery<Q, F = ()>` parameter to enable these read-only scenarios, but I'd rather not add another type to the type zoo.
2021-08-15 20:51:53 +00:00
|
|
|
#[system_param(ignore)]
|
|
|
|
marker: PhantomData<&'s usize>,
|
2021-03-07 20:42:04 +00:00
|
|
|
}
|
|
|
|
|
2022-05-09 13:19:32 +00:00
|
|
|
impl<'w, 's, E: Event> EventWriter<'w, 's, E> {
|
2022-02-04 01:24:47 +00:00
|
|
|
/// Sends an `event`. [`EventReader`]s can then read the event.
|
|
|
|
/// See [`Events`] for details.
|
2022-05-09 13:19:32 +00:00
|
|
|
pub fn send(&mut self, event: E) {
|
2021-03-07 20:42:04 +00:00
|
|
|
self.events.send(event);
|
|
|
|
}
|
|
|
|
|
2022-05-09 13:19:32 +00:00
|
|
|
pub fn send_batch(&mut self, events: impl Iterator<Item = E>) {
|
2021-03-07 20:42:04 +00:00
|
|
|
self.events.extend(events);
|
|
|
|
}
|
2022-02-04 01:24:47 +00:00
|
|
|
|
|
|
|
/// Sends the default value of the event. Useful when the event is an empty struct.
|
|
|
|
pub fn send_default(&mut self)
|
|
|
|
where
|
2022-05-09 13:19:32 +00:00
|
|
|
E: Default,
|
2022-02-04 01:24:47 +00:00
|
|
|
{
|
|
|
|
self.events.send_default();
|
|
|
|
}
|
2021-03-07 20:42:04 +00:00
|
|
|
}
|
|
|
|
|
2022-05-10 20:18:59 +00:00
|
|
|
#[derive(Debug)]
|
2022-05-09 13:19:32 +00:00
|
|
|
pub struct ManualEventReader<E: Event> {
|
2020-03-30 05:44:38 +00:00
|
|
|
last_event_count: usize,
|
2022-05-09 13:19:32 +00:00
|
|
|
_marker: PhantomData<E>,
|
2020-03-30 05:44:38 +00:00
|
|
|
}
|
|
|
|
|
2022-05-09 13:19:32 +00:00
|
|
|
impl<E: Event> Default for ManualEventReader<E> {
|
2020-06-04 06:53:00 +00:00
|
|
|
fn default() -> Self {
|
2021-01-19 06:23:30 +00:00
|
|
|
ManualEventReader {
|
2020-06-04 06:53:00 +00:00
|
|
|
last_event_count: 0,
|
2021-01-19 06:23:30 +00:00
|
|
|
_marker: Default::default(),
|
2020-06-04 06:53:00 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-02-03 23:22:08 +00:00
|
|
|
#[allow(clippy::len_without_is_empty)] // Check fails since the is_empty implementation has a signature other than `(&self) -> bool`
|
2022-05-09 13:19:32 +00:00
|
|
|
impl<E: Event> ManualEventReader<E> {
|
2021-01-19 06:23:30 +00:00
|
|
|
/// See [`EventReader::iter`]
|
2022-05-09 13:19:32 +00:00
|
|
|
pub fn iter<'a>(
|
|
|
|
&'a mut self,
|
|
|
|
events: &'a Events<E>,
|
|
|
|
) -> impl DoubleEndedIterator<Item = &'a E> + ExactSizeIterator<Item = &'a E> {
|
2022-05-10 20:18:59 +00:00
|
|
|
self.iter_with_id(events).map(|(e, _)| e)
|
2020-11-21 22:03:18 +00:00
|
|
|
}
|
|
|
|
|
2021-01-19 06:23:30 +00:00
|
|
|
/// See [`EventReader::iter_with_id`]
|
2020-11-21 22:03:18 +00:00
|
|
|
pub fn iter_with_id<'a>(
|
2022-02-02 02:29:33 +00:00
|
|
|
&'a mut self,
|
2022-05-09 13:19:32 +00:00
|
|
|
events: &'a Events<E>,
|
|
|
|
) -> impl DoubleEndedIterator<Item = (&'a E, EventId<E>)>
|
|
|
|
+ ExactSizeIterator<Item = (&'a E, EventId<E>)> {
|
2022-05-10 20:18:59 +00:00
|
|
|
// if the reader has seen some of the events in a buffer, find the proper index offset.
|
|
|
|
// otherwise read all events in the buffer
|
|
|
|
let a_index = (self.last_event_count).saturating_sub(events.events_a.start_event_count);
|
|
|
|
let b_index = (self.last_event_count).saturating_sub(events.events_b.start_event_count);
|
|
|
|
let a = events.events_a.get(a_index..).unwrap_or_default();
|
|
|
|
let b = events.events_b.get(b_index..).unwrap_or_default();
|
|
|
|
let unread_count = a.len() + b.len();
|
|
|
|
// Ensure `len` is implemented correctly
|
|
|
|
debug_assert_eq!(unread_count, self.len(events));
|
|
|
|
self.last_event_count = events.event_count - unread_count;
|
|
|
|
// Iterate the oldest first, then the newer events
|
|
|
|
let iterator = a.iter().chain(b.iter());
|
|
|
|
iterator
|
|
|
|
.map(|e| (&e.event, e.event_id))
|
|
|
|
.with_exact_size(unread_count)
|
|
|
|
.inspect(move |(_, id)| self.last_event_count = (id.id + 1).max(self.last_event_count))
|
2020-11-21 22:03:18 +00:00
|
|
|
}
|
2022-02-03 23:22:08 +00:00
|
|
|
|
|
|
|
/// See [`EventReader::len`]
|
2022-05-09 13:19:32 +00:00
|
|
|
pub fn len(&self, events: &Events<E>) -> usize {
|
2022-05-10 20:18:59 +00:00
|
|
|
// The number of events in this reader is the difference between the most recent event
|
|
|
|
// and the last event seen by it. This will be at most the number of events contained
|
|
|
|
// with the events (any others have already been dropped)
|
|
|
|
// TODO: Warn when there are dropped events, or return e.g. a `Result<usize, (usize, usize)>`
|
|
|
|
events
|
|
|
|
.event_count
|
|
|
|
.saturating_sub(self.last_event_count)
|
|
|
|
.min(events.len())
|
2022-02-03 23:22:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// See [`EventReader::is_empty`]
|
2022-05-09 13:19:32 +00:00
|
|
|
pub fn is_empty(&self, events: &Events<E>) -> bool {
|
2022-02-03 23:22:08 +00:00
|
|
|
self.len(events) == 0
|
|
|
|
}
|
2021-01-19 06:23:30 +00:00
|
|
|
}
|
2020-11-21 22:03:18 +00:00
|
|
|
|
2022-05-09 13:19:32 +00:00
|
|
|
trait IteratorExt {
|
|
|
|
fn with_exact_size(self, len: usize) -> ExactSize<Self>
|
|
|
|
where
|
|
|
|
Self: Sized,
|
|
|
|
{
|
|
|
|
ExactSize::new(self, len)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
impl<I> IteratorExt for I where I: Iterator {}
|
|
|
|
|
|
|
|
#[must_use = "iterators are lazy and do nothing unless consumed"]
|
|
|
|
#[derive(Clone)]
|
|
|
|
struct ExactSize<I> {
|
|
|
|
iter: I,
|
|
|
|
len: usize,
|
|
|
|
}
|
|
|
|
impl<I> ExactSize<I> {
|
|
|
|
fn new(iter: I, len: usize) -> Self {
|
|
|
|
ExactSize { iter, len }
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<I: Iterator> Iterator for ExactSize<I> {
|
|
|
|
type Item = I::Item;
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
fn next(&mut self) -> Option<I::Item> {
|
|
|
|
self.iter.next().map(|e| {
|
|
|
|
self.len -= 1;
|
|
|
|
e
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
#[inline]
|
|
|
|
fn size_hint(&self) -> (usize, Option<usize>) {
|
|
|
|
(self.len, Some(self.len))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<I: DoubleEndedIterator> DoubleEndedIterator for ExactSize<I> {
|
|
|
|
#[inline]
|
|
|
|
fn next_back(&mut self) -> Option<I::Item> {
|
|
|
|
self.iter.next_back().map(|e| {
|
|
|
|
self.len -= 1;
|
|
|
|
e
|
|
|
|
})
|
|
|
|
}
|
|
|
|
}
|
|
|
|
impl<I: Iterator> ExactSizeIterator for ExactSize<I> {
|
|
|
|
fn len(&self) -> usize {
|
|
|
|
self.len
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<E: Event> Events<E> {
|
2022-01-06 00:43:37 +00:00
|
|
|
/// "Sends" an `event` by writing it to the current event buffer. [`EventReader`]s can then read
|
2021-03-11 00:27:30 +00:00
|
|
|
/// the event.
|
2022-05-09 13:19:32 +00:00
|
|
|
pub fn send(&mut self, event: E) {
|
2020-11-21 22:03:18 +00:00
|
|
|
let event_id = EventId {
|
|
|
|
id: self.event_count,
|
|
|
|
_marker: PhantomData,
|
2020-04-28 17:59:42 +00:00
|
|
|
};
|
2021-05-19 18:41:46 +00:00
|
|
|
trace!("Events::send() -> id: {}", event_id);
|
2020-11-21 22:03:18 +00:00
|
|
|
|
2021-03-25 20:48:18 +00:00
|
|
|
let event_instance = EventInstance { event_id, event };
|
2020-04-28 17:59:42 +00:00
|
|
|
|
2022-05-10 20:18:59 +00:00
|
|
|
self.events_b.push(event_instance);
|
2020-04-28 17:59:42 +00:00
|
|
|
self.event_count += 1;
|
2020-04-16 18:16:22 +00:00
|
|
|
}
|
|
|
|
|
2022-02-04 01:24:47 +00:00
|
|
|
/// Sends the default value of the event. Useful when the event is an empty struct.
|
|
|
|
pub fn send_default(&mut self)
|
|
|
|
where
|
2022-05-09 13:19:32 +00:00
|
|
|
E: Default,
|
2022-02-04 01:24:47 +00:00
|
|
|
{
|
|
|
|
self.send(Default::default());
|
|
|
|
}
|
|
|
|
|
2022-01-06 00:43:37 +00:00
|
|
|
/// Gets a new [`ManualEventReader`]. This will include all events already in the event buffers.
|
2022-05-09 13:19:32 +00:00
|
|
|
pub fn get_reader(&self) -> ManualEventReader<E> {
|
2022-05-10 20:18:59 +00:00
|
|
|
ManualEventReader::default()
|
2020-03-30 05:44:38 +00:00
|
|
|
}
|
|
|
|
|
2022-01-06 00:43:37 +00:00
|
|
|
/// Gets a new [`ManualEventReader`]. This will ignore all events already in the event buffers.
|
|
|
|
/// It will read all future events.
|
2022-05-09 13:19:32 +00:00
|
|
|
pub fn get_reader_current(&self) -> ManualEventReader<E> {
|
2021-01-19 06:23:30 +00:00
|
|
|
ManualEventReader {
|
2020-04-01 01:04:54 +00:00
|
|
|
last_event_count: self.event_count,
|
2022-05-10 20:18:59 +00:00
|
|
|
..Default::default()
|
2020-04-01 01:04:54 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-03-11 00:27:30 +00:00
|
|
|
/// Swaps the event buffers and clears the oldest event buffer. In general, this should be
|
|
|
|
/// called once per frame/update.
|
2020-03-30 05:44:38 +00:00
|
|
|
pub fn update(&mut self) {
|
2022-05-10 20:18:59 +00:00
|
|
|
std::mem::swap(&mut self.events_a, &mut self.events_b);
|
|
|
|
self.events_b.clear();
|
|
|
|
self.events_b.start_event_count = self.event_count;
|
|
|
|
debug_assert_eq!(
|
|
|
|
self.events_a.start_event_count + self.events_a.len(),
|
|
|
|
self.events_b.start_event_count
|
|
|
|
);
|
2020-03-30 05:44:38 +00:00
|
|
|
}
|
|
|
|
|
2022-01-06 00:43:37 +00:00
|
|
|
/// A system that calls [`Events::update`] once per frame.
|
2020-05-14 00:52:47 +00:00
|
|
|
pub fn update_system(mut events: ResMut<Self>) {
|
2020-04-30 23:19:28 +00:00
|
|
|
events.update();
|
2020-03-30 05:44:38 +00:00
|
|
|
}
|
2020-05-13 23:17:06 +00:00
|
|
|
|
2021-05-19 03:41:28 +00:00
|
|
|
#[inline]
|
|
|
|
fn reset_start_event_count(&mut self) {
|
2022-05-10 20:18:59 +00:00
|
|
|
self.events_a.start_event_count = self.event_count;
|
|
|
|
self.events_b.start_event_count = self.event_count;
|
2021-05-19 03:41:28 +00:00
|
|
|
}
|
|
|
|
|
2020-05-13 23:17:06 +00:00
|
|
|
/// Removes all events.
|
2021-05-19 03:41:28 +00:00
|
|
|
#[inline]
|
2020-05-13 23:17:06 +00:00
|
|
|
pub fn clear(&mut self) {
|
2021-05-19 03:41:28 +00:00
|
|
|
self.reset_start_event_count();
|
2020-05-13 23:17:06 +00:00
|
|
|
self.events_a.clear();
|
|
|
|
self.events_b.clear();
|
|
|
|
}
|
|
|
|
|
2022-05-10 20:18:59 +00:00
|
|
|
#[inline]
|
|
|
|
pub fn len(&self) -> usize {
|
|
|
|
self.events_a.len() + self.events_b.len()
|
|
|
|
}
|
|
|
|
|
2021-06-02 02:30:14 +00:00
|
|
|
/// Returns true if there are no events in this collection.
|
|
|
|
#[inline]
|
|
|
|
pub fn is_empty(&self) -> bool {
|
2022-05-10 20:18:59 +00:00
|
|
|
self.len() == 0
|
2021-06-02 02:30:14 +00:00
|
|
|
}
|
|
|
|
|
2020-05-13 23:17:06 +00:00
|
|
|
/// Creates a draining iterator that removes all events.
|
2022-05-09 13:19:32 +00:00
|
|
|
pub fn drain(&mut self) -> impl Iterator<Item = E> + '_ {
|
2021-05-19 03:41:28 +00:00
|
|
|
self.reset_start_event_count();
|
|
|
|
|
2022-05-10 20:18:59 +00:00
|
|
|
// Drain the oldest events first, then the newest
|
|
|
|
self.events_a
|
|
|
|
.drain(..)
|
|
|
|
.chain(self.events_b.drain(..))
|
|
|
|
.map(|i| i.event)
|
2020-05-13 23:17:06 +00:00
|
|
|
}
|
|
|
|
|
2020-06-17 05:20:08 +00:00
|
|
|
/// Iterates over events that happened since the last "update" call.
|
2021-03-11 00:27:30 +00:00
|
|
|
/// WARNING: You probably don't want to use this call. In most cases you should use an
|
2022-02-03 23:22:08 +00:00
|
|
|
/// [`EventReader`]. You should only use this if you know you only need to consume events
|
2021-03-11 00:27:30 +00:00
|
|
|
/// between the last `update()` call and your call to `iter_current_update_events`.
|
|
|
|
/// If events happen outside that window, they will not be handled. For example, any events that
|
|
|
|
/// happen after this call and before the next `update()` call will be dropped.
|
2022-05-09 13:19:32 +00:00
|
|
|
pub fn iter_current_update_events(
|
|
|
|
&self,
|
|
|
|
) -> impl DoubleEndedIterator<Item = &E> + ExactSizeIterator<Item = &E> {
|
2022-05-10 20:18:59 +00:00
|
|
|
self.events_b.iter().map(|i| &i.event)
|
2020-06-17 05:20:08 +00:00
|
|
|
}
|
2020-03-30 05:44:38 +00:00
|
|
|
}
|
2020-03-30 21:53:32 +00:00
|
|
|
|
2022-05-09 13:19:32 +00:00
|
|
|
impl<E: Event> std::iter::Extend<E> for Events<E> {
|
2021-05-19 18:41:46 +00:00
|
|
|
fn extend<I>(&mut self, iter: I)
|
|
|
|
where
|
2022-05-09 13:19:32 +00:00
|
|
|
I: IntoIterator<Item = E>,
|
2021-05-19 18:41:46 +00:00
|
|
|
{
|
|
|
|
let mut event_count = self.event_count;
|
|
|
|
let events = iter.into_iter().map(|event| {
|
|
|
|
let event_id = EventId {
|
|
|
|
id: event_count,
|
|
|
|
_marker: PhantomData,
|
|
|
|
};
|
|
|
|
event_count += 1;
|
|
|
|
EventInstance { event_id, event }
|
|
|
|
});
|
|
|
|
|
2022-05-10 20:18:59 +00:00
|
|
|
self.events_b.extend(events);
|
2021-05-19 18:41:46 +00:00
|
|
|
|
|
|
|
trace!(
|
|
|
|
"Events::extend() -> ids: ({}..{})",
|
|
|
|
self.event_count,
|
|
|
|
event_count
|
|
|
|
);
|
|
|
|
self.event_count = event_count;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-04-01 01:04:54 +00:00
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
2022-05-09 16:09:33 +00:00
|
|
|
use crate::{prelude::World, system::SystemState};
|
|
|
|
|
2020-04-01 01:04:54 +00:00
|
|
|
use super::*;
|
|
|
|
|
|
|
|
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
|
|
|
|
struct TestEvent {
|
|
|
|
i: usize,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_events() {
|
|
|
|
let mut events = Events::<TestEvent>::default();
|
|
|
|
let event_0 = TestEvent { i: 0 };
|
|
|
|
let event_1 = TestEvent { i: 1 };
|
|
|
|
let event_2 = TestEvent { i: 2 };
|
|
|
|
|
2021-03-11 00:27:30 +00:00
|
|
|
// this reader will miss event_0 and event_1 because it wont read them over the course of
|
|
|
|
// two updates
|
2020-04-01 01:04:54 +00:00
|
|
|
let mut reader_missed = events.get_reader();
|
|
|
|
|
|
|
|
let mut reader_a = events.get_reader();
|
|
|
|
|
|
|
|
events.send(event_0);
|
|
|
|
|
|
|
|
assert_eq!(
|
|
|
|
get_events(&events, &mut reader_a),
|
|
|
|
vec![event_0],
|
|
|
|
"reader_a created before event receives event"
|
|
|
|
);
|
|
|
|
assert_eq!(
|
|
|
|
get_events(&events, &mut reader_a),
|
|
|
|
vec![],
|
|
|
|
"second iteration of reader_a created before event results in zero events"
|
|
|
|
);
|
|
|
|
|
|
|
|
let mut reader_b = events.get_reader();
|
|
|
|
|
|
|
|
assert_eq!(
|
|
|
|
get_events(&events, &mut reader_b),
|
|
|
|
vec![event_0],
|
|
|
|
"reader_b created after event receives event"
|
|
|
|
);
|
|
|
|
assert_eq!(
|
|
|
|
get_events(&events, &mut reader_b),
|
|
|
|
vec![],
|
|
|
|
"second iteration of reader_b created after event results in zero events"
|
|
|
|
);
|
|
|
|
|
|
|
|
events.send(event_1);
|
|
|
|
|
|
|
|
let mut reader_c = events.get_reader();
|
|
|
|
|
|
|
|
assert_eq!(
|
|
|
|
get_events(&events, &mut reader_c),
|
|
|
|
vec![event_0, event_1],
|
|
|
|
"reader_c created after two events receives both events"
|
|
|
|
);
|
|
|
|
assert_eq!(
|
|
|
|
get_events(&events, &mut reader_c),
|
|
|
|
vec![],
|
|
|
|
"second iteration of reader_c created after two event results in zero events"
|
|
|
|
);
|
|
|
|
|
|
|
|
assert_eq!(
|
|
|
|
get_events(&events, &mut reader_a),
|
|
|
|
vec![event_1],
|
|
|
|
"reader_a receives next unread event"
|
|
|
|
);
|
|
|
|
|
|
|
|
events.update();
|
|
|
|
|
|
|
|
let mut reader_d = events.get_reader();
|
|
|
|
|
|
|
|
events.send(event_2);
|
|
|
|
|
|
|
|
assert_eq!(
|
|
|
|
get_events(&events, &mut reader_a),
|
|
|
|
vec![event_2],
|
|
|
|
"reader_a receives event created after update"
|
|
|
|
);
|
|
|
|
assert_eq!(
|
|
|
|
get_events(&events, &mut reader_b),
|
|
|
|
vec![event_1, event_2],
|
|
|
|
"reader_b receives events created before and after update"
|
|
|
|
);
|
|
|
|
assert_eq!(
|
|
|
|
get_events(&events, &mut reader_d),
|
|
|
|
vec![event_0, event_1, event_2],
|
|
|
|
"reader_d receives all events created before and after update"
|
|
|
|
);
|
|
|
|
|
|
|
|
events.update();
|
|
|
|
|
|
|
|
assert_eq!(
|
|
|
|
get_events(&events, &mut reader_missed),
|
|
|
|
vec![event_2],
|
2021-09-13 17:37:51 +00:00
|
|
|
"reader_missed missed events unread after two update() calls"
|
2020-04-01 01:04:54 +00:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2022-05-09 13:19:32 +00:00
|
|
|
fn get_events<E: Event + Clone>(
|
|
|
|
events: &Events<E>,
|
|
|
|
reader: &mut ManualEventReader<E>,
|
|
|
|
) -> Vec<E> {
|
|
|
|
reader.iter(events).cloned().collect::<Vec<E>>()
|
2020-03-30 21:53:32 +00:00
|
|
|
}
|
2021-05-19 03:41:28 +00:00
|
|
|
|
|
|
|
#[derive(PartialEq, Eq, Debug)]
|
|
|
|
struct E(usize);
|
|
|
|
|
|
|
|
fn events_clear_and_read_impl(clear_func: impl FnOnce(&mut Events<E>)) {
|
|
|
|
let mut events = Events::<E>::default();
|
|
|
|
let mut reader = events.get_reader();
|
|
|
|
|
|
|
|
assert!(reader.iter(&events).next().is_none());
|
|
|
|
|
|
|
|
events.send(E(0));
|
|
|
|
assert_eq!(*reader.iter(&events).next().unwrap(), E(0));
|
|
|
|
assert_eq!(reader.iter(&events).next(), None);
|
|
|
|
|
|
|
|
events.send(E(1));
|
|
|
|
clear_func(&mut events);
|
|
|
|
assert!(reader.iter(&events).next().is_none());
|
|
|
|
|
|
|
|
events.send(E(2));
|
|
|
|
events.update();
|
|
|
|
events.send(E(3));
|
|
|
|
|
|
|
|
assert!(reader.iter(&events).eq([E(2), E(3)].iter()));
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_events_clear_and_read() {
|
|
|
|
events_clear_and_read_impl(|events| events.clear());
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_events_drain_and_read() {
|
|
|
|
events_clear_and_read_impl(|events| {
|
|
|
|
assert!(events.drain().eq(vec![E(0), E(1)].into_iter()));
|
|
|
|
});
|
|
|
|
}
|
2021-05-19 18:41:46 +00:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_events_extend_impl() {
|
|
|
|
let mut events = Events::<TestEvent>::default();
|
|
|
|
let mut reader = events.get_reader();
|
|
|
|
|
|
|
|
events.extend(vec![TestEvent { i: 0 }, TestEvent { i: 1 }]);
|
|
|
|
assert!(reader
|
|
|
|
.iter(&events)
|
|
|
|
.eq([TestEvent { i: 0 }, TestEvent { i: 1 }].iter()));
|
|
|
|
}
|
2021-06-02 02:30:14 +00:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_events_empty() {
|
|
|
|
let mut events = Events::<TestEvent>::default();
|
|
|
|
assert!(events.is_empty());
|
|
|
|
|
|
|
|
events.send(TestEvent { i: 0 });
|
|
|
|
assert!(!events.is_empty());
|
|
|
|
|
|
|
|
events.update();
|
|
|
|
assert!(!events.is_empty());
|
|
|
|
|
|
|
|
// events are only empty after the second call to update
|
|
|
|
// due to double buffering.
|
|
|
|
events.update();
|
|
|
|
assert!(events.is_empty());
|
|
|
|
}
|
2022-02-03 23:22:08 +00:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_event_reader_len_empty() {
|
|
|
|
let events = Events::<TestEvent>::default();
|
|
|
|
assert_eq!(events.get_reader().len(&events), 0);
|
|
|
|
assert!(events.get_reader().is_empty(&events));
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_event_reader_len_filled() {
|
|
|
|
let mut events = Events::<TestEvent>::default();
|
|
|
|
events.send(TestEvent { i: 0 });
|
|
|
|
assert_eq!(events.get_reader().len(&events), 1);
|
|
|
|
assert!(!events.get_reader().is_empty(&events));
|
|
|
|
}
|
|
|
|
|
2022-05-09 13:19:32 +00:00
|
|
|
#[test]
|
|
|
|
fn test_event_iter_len_updated() {
|
|
|
|
let mut events = Events::<TestEvent>::default();
|
|
|
|
events.send(TestEvent { i: 0 });
|
|
|
|
events.send(TestEvent { i: 1 });
|
|
|
|
events.send(TestEvent { i: 2 });
|
|
|
|
let mut reader = events.get_reader();
|
|
|
|
let mut iter = reader.iter(&events);
|
|
|
|
assert_eq!(iter.len(), 3);
|
|
|
|
iter.next();
|
|
|
|
assert_eq!(iter.len(), 2);
|
|
|
|
iter.next_back();
|
|
|
|
assert_eq!(iter.len(), 1);
|
|
|
|
}
|
|
|
|
|
2022-02-03 23:22:08 +00:00
|
|
|
#[test]
|
|
|
|
fn test_event_reader_len_current() {
|
|
|
|
let mut events = Events::<TestEvent>::default();
|
|
|
|
events.send(TestEvent { i: 0 });
|
|
|
|
let reader = events.get_reader_current();
|
2022-05-10 20:18:59 +00:00
|
|
|
dbg!(&reader);
|
|
|
|
dbg!(&events);
|
2022-02-03 23:22:08 +00:00
|
|
|
assert!(reader.is_empty(&events));
|
|
|
|
events.send(TestEvent { i: 0 });
|
|
|
|
assert_eq!(reader.len(&events), 1);
|
|
|
|
assert!(!reader.is_empty(&events));
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_event_reader_len_update() {
|
|
|
|
let mut events = Events::<TestEvent>::default();
|
|
|
|
events.send(TestEvent { i: 0 });
|
|
|
|
events.send(TestEvent { i: 0 });
|
|
|
|
let reader = events.get_reader();
|
|
|
|
assert_eq!(reader.len(&events), 2);
|
|
|
|
events.update();
|
|
|
|
events.send(TestEvent { i: 0 });
|
|
|
|
assert_eq!(reader.len(&events), 3);
|
|
|
|
events.update();
|
|
|
|
assert_eq!(reader.len(&events), 1);
|
|
|
|
events.update();
|
|
|
|
assert!(reader.is_empty(&events));
|
|
|
|
}
|
2022-02-04 01:24:47 +00:00
|
|
|
|
2022-05-13 00:57:04 +00:00
|
|
|
#[test]
|
|
|
|
fn test_event_reader_clear() {
|
|
|
|
use bevy_ecs::prelude::*;
|
|
|
|
|
|
|
|
let mut world = World::new();
|
|
|
|
let mut events = Events::<TestEvent>::default();
|
|
|
|
events.send(TestEvent { i: 0 });
|
|
|
|
world.insert_resource(events);
|
|
|
|
|
|
|
|
let mut reader = IntoSystem::into_system(|events: EventReader<TestEvent>| -> bool {
|
|
|
|
if !events.is_empty() {
|
|
|
|
events.clear();
|
|
|
|
false
|
|
|
|
} else {
|
|
|
|
true
|
|
|
|
}
|
|
|
|
});
|
|
|
|
reader.initialize(&mut world);
|
|
|
|
|
|
|
|
let is_empty = reader.run((), &mut world);
|
|
|
|
assert!(!is_empty, "EventReader should not be empty");
|
|
|
|
let is_empty = reader.run((), &mut world);
|
|
|
|
assert!(is_empty, "EventReader should be empty");
|
|
|
|
}
|
|
|
|
|
2022-02-04 01:24:47 +00:00
|
|
|
#[derive(Clone, PartialEq, Debug, Default)]
|
|
|
|
struct EmptyTestEvent;
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_firing_empty_event() {
|
|
|
|
let mut events = Events::<EmptyTestEvent>::default();
|
|
|
|
events.send_default();
|
|
|
|
|
|
|
|
let mut reader = events.get_reader();
|
|
|
|
assert_eq!(
|
|
|
|
get_events(&events, &mut reader),
|
|
|
|
vec![EmptyTestEvent::default()]
|
|
|
|
);
|
|
|
|
}
|
2022-05-09 16:09:33 +00:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn ensure_reader_readonly() {
|
|
|
|
fn read_for<E: Event>() {
|
|
|
|
let mut world = World::new();
|
|
|
|
world.init_resource::<Events<E>>();
|
|
|
|
let mut state = SystemState::<EventReader<E>>::new(&mut world);
|
|
|
|
// This can only work if EventReader only reads the world
|
|
|
|
let _reader = state.get(&world);
|
|
|
|
}
|
|
|
|
read_for::<EmptyTestEvent>();
|
|
|
|
}
|
2020-03-30 21:53:32 +00:00
|
|
|
}
|