-
-
Notifications
You must be signed in to change notification settings - Fork 4.6k
Tracked one-shot systems #24165
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ItsDoot
wants to merge
5
commits into
bevyengine:main
Choose a base branch
from
ItsDoot:ecs/optinoneshothandle
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Tracked one-shot systems #24165
Changes from 4 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -5,13 +5,16 @@ use crate::{ | |
| entity::Entity, | ||
| error::BevyError, | ||
| system::{ | ||
| input::SystemInput, BoxedSystem, IntoSystem, RunSystemError, SystemParamValidationError, | ||
| input::SystemInput, BoxedSystem, Commands, If, IntoSystem, Res, RunSystemError, | ||
| SystemParamValidationError, | ||
| }, | ||
| world::World, | ||
| }; | ||
| use alloc::boxed::Box; | ||
| use bevy_ecs_macros::{Component, Resource}; | ||
| use bevy_platform::sync::Arc; | ||
| use bevy_utils::prelude::DebugName; | ||
| use concurrent_queue::ConcurrentQueue; | ||
| use core::{any::TypeId, marker::PhantomData}; | ||
| use thiserror::Error; | ||
|
|
||
|
|
@@ -94,6 +97,135 @@ impl<I, O> RemovedSystem<I, O> { | |
| } | ||
| } | ||
|
|
||
| /// A system that despawns any registered system entities whose [`SystemHandle`] | ||
| /// reference count has reached zero. | ||
| pub fn despawn_unused_registered_systems( | ||
| // `RegisteredSystemDespawner` is initialized lazily the first time a system | ||
| // is registered, so it's possible that it doesn't exist yet when this system runs. | ||
| despawner: If<Res<RegisteredSystemDespawner>>, | ||
| mut commands: Commands, | ||
| ) { | ||
| while let Ok(entity) = despawner.queue.pop() { | ||
| // In case the entity was already despawned manually, we ignore the error here. | ||
| commands.entity(entity).try_despawn(); | ||
| } | ||
| } | ||
|
|
||
| /// A resource that stores the channel for despawning unused registered system | ||
| /// entities. | ||
| #[derive(Resource)] | ||
| pub struct RegisteredSystemDespawner { | ||
| queue: Arc<ConcurrentQueue<Entity>>, | ||
| } | ||
|
|
||
| impl Default for RegisteredSystemDespawner { | ||
| fn default() -> Self { | ||
| Self { | ||
| queue: Arc::new(ConcurrentQueue::unbounded()), | ||
| } | ||
| } | ||
| } | ||
|
|
||
| /// A maybe-strong handle to an entity acting as a registered system. Strong | ||
| /// handles are created by [`World::register_tracked_system`] or | ||
| /// [`World::register_tracked_boxed_system`]. | ||
| /// | ||
| /// Strong handles provide automatic cleanup of registered systems once all clones | ||
| /// of the handle are dropped, while weak handles do not. However, the **existence | ||
| /// of a strong handle does not prevent the registered system entity from being | ||
| /// despawned manually**, like with [`World::unregister_system`] or | ||
| /// [`World::unregister_system_cached`]. | ||
| /// | ||
| /// # Cleanup | ||
| /// | ||
| /// Registered system entities are cleaned up by the [`despawn_unused_registered_systems`] | ||
| /// system, which is automatically added to the default app by the `bevy_app` | ||
| /// crate when the "std" feature is enabled. If not using the default app, the | ||
| /// "std" feature, or `bevy_app` in general, consider running this system | ||
| /// yourself to ensure proper cleanup of registered systems. | ||
| pub enum SystemHandle<I: SystemInput = (), O = ()> { | ||
| /// A strong handle keeps the system entity alive as long as the handle | ||
| /// (and any clones of it) exist, as long as the system entity isn't | ||
| /// manually despawned. | ||
| Strong(Arc<StrongSystemHandle>), | ||
| /// A weak handle does not keep the system entity alive. | ||
| Weak(SystemId<I, O>), | ||
| } | ||
|
|
||
| impl<I: SystemInput, O> SystemHandle<I, O> { | ||
| /// Returns the [`Entity`] of the registered system associated with this handle. | ||
| pub fn entity(&self) -> Entity { | ||
| match self { | ||
| SystemHandle::Strong(strong) => strong.entity, | ||
| SystemHandle::Weak(weak) => weak.entity, | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl<I: SystemInput, O> Eq for SystemHandle<I, O> {} | ||
|
|
||
| // A manual impl is used because the trait bounds should ignore the `I` and `O` phantom parameters. | ||
| impl<I: SystemInput, O> Clone for SystemHandle<I, O> { | ||
| fn clone(&self) -> Self { | ||
| match self { | ||
| SystemHandle::Strong(strong) => SystemHandle::Strong(Arc::clone(strong)), | ||
| SystemHandle::Weak(weak) => SystemHandle::Weak(*weak), | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // A manual impl is used because the trait bounds should ignore the `I` and `O` phantom parameters, | ||
| // and so that strong and weak handles can be compared for equality based on their entities. | ||
| impl<I: SystemInput, O> PartialEq for SystemHandle<I, O> { | ||
| fn eq(&self, other: &Self) -> bool { | ||
| self.entity() == other.entity() | ||
| } | ||
| } | ||
|
|
||
| impl<I: SystemInput, O> PartialEq<SystemId<I, O>> for SystemHandle<I, O> { | ||
| fn eq(&self, other: &SystemId<I, O>) -> bool { | ||
| self.entity() == other.entity | ||
| } | ||
| } | ||
|
|
||
| // A manual impl is used because the trait bounds should ignore the `I` and `O` phantom parameters, | ||
| // and so that the handle can be hashed based on its entity not its handle type. | ||
| impl<I: SystemInput, O> core::hash::Hash for SystemHandle<I, O> { | ||
| fn hash<H: core::hash::Hasher>(&self, state: &mut H) { | ||
| self.entity().hash(state); | ||
| } | ||
| } | ||
|
|
||
| impl<I: SystemInput, O> core::fmt::Debug for SystemHandle<I, O> { | ||
| fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { | ||
| let name = if matches!(self, SystemHandle::Strong(_)) { | ||
| "StrongSystemHandle" | ||
| } else { | ||
| "WeakSystemHandle" | ||
| }; | ||
| f.debug_tuple(name).field(&self.entity()).finish() | ||
| } | ||
| } | ||
|
|
||
| impl<I: SystemInput, O> From<SystemId<I, O>> for SystemHandle<I, O> { | ||
| fn from(id: SystemId<I, O>) -> Self { | ||
| SystemHandle::Weak(id) | ||
| } | ||
| } | ||
|
|
||
| /// A strong handle for a registered system that despawns the entity when dropped. | ||
| pub struct StrongSystemHandle { | ||
| entity: Entity, | ||
| drop_queue: Arc<ConcurrentQueue<Entity>>, | ||
| } | ||
|
|
||
| impl Drop for StrongSystemHandle { | ||
| fn drop(&mut self) { | ||
| // Send the entity to be despawned by the world when the last strong handle is dropped. | ||
| let _ = self.drop_queue.push(self.entity); | ||
| } | ||
| } | ||
|
|
||
| /// An identifier for a registered system. | ||
| /// | ||
| /// These are opaque identifiers, keyed to a specific [`World`], | ||
|
|
@@ -214,6 +346,51 @@ impl World { | |
| SystemId::from_entity(entity) | ||
| } | ||
|
|
||
| /// Registers a system and returns a tracked [`SystemHandle`] so it can later | ||
| /// be called by [`World::run_system`]. The system entity will be automatically | ||
| /// queued for despawn when the last clone of the returned handle is dropped. | ||
| /// | ||
| /// By default, unused tracked system entities are despawned by the | ||
| /// [`despawn_unused_registered_systems`] system in the `Last` schedule of | ||
| /// the default app. Otherwise, it needs to be run manually to ensure proper | ||
| /// cleanup of registered systems. | ||
| /// | ||
| /// It's possible to register multiple copies of the same system by calling | ||
| /// this function multiple times. If that's not what you want, consider using | ||
| /// [`World::register_system_cached`] instead. | ||
| pub fn register_tracked_system<I, O, M>( | ||
| &mut self, | ||
| system: impl IntoSystem<I, O, M> + 'static, | ||
| ) -> SystemHandle<I, O> | ||
| where | ||
| I: SystemInput + 'static, | ||
| O: 'static, | ||
| { | ||
| self.register_tracked_boxed_system(Box::new(IntoSystem::into_system(system))) | ||
| } | ||
|
|
||
| /// Similar to [`Self::register_tracked_system`], but allows passing in a | ||
| /// [`BoxedSystem`]. | ||
| /// | ||
| /// This is useful if the [`IntoSystem`] implementor has already been turned | ||
| /// into a [`System`](crate::system::System) trait object and put in a [`Box`]. | ||
| pub fn register_tracked_boxed_system<I, O>( | ||
| &mut self, | ||
| system: BoxedSystem<I, O>, | ||
| ) -> SystemHandle<I, O> | ||
| where | ||
| I: SystemInput + 'static, | ||
| O: 'static, | ||
| { | ||
| let entity = self.spawn(RegisteredSystem::new(system)).id(); | ||
| let despawner = self.get_resource_or_init::<RegisteredSystemDespawner>(); | ||
|
|
||
| SystemHandle::Strong(Arc::new(StrongSystemHandle { | ||
| entity, | ||
| drop_queue: despawner.queue.clone(), | ||
| })) | ||
| } | ||
|
|
||
| /// Removes a registered system and returns the system, if it exists. | ||
| /// After removing a system, the [`SystemId`] becomes invalid and attempting to use it afterwards will result in errors. | ||
| /// Re-adding the removed system will register it on a new [`SystemId`]. | ||
|
|
@@ -332,7 +509,7 @@ impl World { | |
| /// ``` | ||
| pub fn run_system<O: 'static>( | ||
| &mut self, | ||
| id: SystemId<(), O>, | ||
| id: impl Into<SystemId<(), O>>, | ||
| ) -> Result<O, RegisteredSystemError<(), O>> { | ||
| self.run_system_with(id, ()) | ||
| } | ||
|
|
@@ -364,13 +541,14 @@ impl World { | |
| /// See [`World::run_system`] for more examples. | ||
| pub fn run_system_with<I, O>( | ||
| &mut self, | ||
| id: SystemId<I, O>, | ||
| id: impl Into<SystemId<I, O>>, | ||
| input: I::Inner<'_>, | ||
| ) -> Result<O, RegisteredSystemError<I, O>> | ||
| where | ||
| I: SystemInput + 'static, | ||
| O: 'static, | ||
| { | ||
| let id = id.into(); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Do we need to worry about this monomorphizing two versions of this function?
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Maybe! Would be good to check how much of a difference the codegen is |
||
| // Lookup | ||
| let mut entity = self | ||
| .get_entity_mut(id.entity) | ||
|
|
@@ -604,7 +782,7 @@ mod tests { | |
|
|
||
| use crate::{ | ||
| prelude::*, | ||
| system::{RegisteredSystemError, SystemId}, | ||
| system::{despawn_unused_registered_systems, RegisteredSystemError, SystemId}, | ||
| }; | ||
|
|
||
| #[derive(Resource, Default, PartialEq, Debug)] | ||
|
|
@@ -1074,4 +1252,23 @@ mod tests { | |
| Err(err) => panic!("Failed with wrong error. `{:?}`", err), | ||
| } | ||
| } | ||
|
|
||
| #[test] | ||
| fn despawn_unused() { | ||
| let mut world = World::new(); | ||
|
|
||
| fn system() {} | ||
|
|
||
| let handle = world.register_tracked_system(system); | ||
| let entity = handle.entity(); | ||
| drop(handle); | ||
|
|
||
| assert!(world.get_entity(entity).is_ok()); | ||
|
|
||
| world | ||
| .run_system_cached(despawn_unused_registered_systems) | ||
| .unwrap(); | ||
|
|
||
| assert!(world.get_entity(entity).is_err()); | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.