-
-
Notifications
You must be signed in to change notification settings - Fork 4.5k
Schedule enter and exit hooks #23738
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
MushineLament
wants to merge
5
commits into
bevyengine:main
Choose a base branch
from
MushineLament:schedulehook
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.
+185
−6
Open
Changes from 1 commit
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,174 @@ | ||
| //! This is about hooks for the [`Schedule`](super::Schedule) execution phases, | ||
| //! aiming to handle instructions triggered either before entering the [`Schedule`] or after exiting it. | ||
| use crate::world::World; | ||
| use crate::{intern::Interned, prelude::Resource, schedule::ScheduleLabel, system::SystemId}; | ||
| use bevy_platform::collections::HashMap; | ||
| use bevy_platform::prelude::vec::Vec; | ||
| use log::error; | ||
|
|
||
| /// Used to control whether to retain or remove the [`ScheduleHook`] after it is triggered. | ||
| #[derive(Debug, Clone, PartialEq, Eq, Copy, Hash)] | ||
| pub enum ScheduleHookPlan { | ||
| /// Remove after executing the [`ScheduleHook`] | ||
| Clear, | ||
| /// Keep after executing the [`ScheduleHook`] | ||
| Keep, | ||
| } | ||
|
|
||
| /// Every valid [`Schedule`](super::Schedule) hook is a system that returns a [ScheduleHookPlan]. | ||
| pub type ScheduleHook = SystemId<(), ScheduleHookPlan>; | ||
|
|
||
| /// The hub for managing [`ScheduleHook`], used to control when hooks are triggered. | ||
| #[derive(Debug, Resource, Default, Clone)] | ||
| pub struct ScheduleHooks { | ||
| enter: HashMap<Interned<dyn ScheduleLabel>, Vec<ScheduleHook>>, | ||
| exit: HashMap<Interned<dyn ScheduleLabel>, Vec<ScheduleHook>>, | ||
| } | ||
|
|
||
| impl ScheduleHooks { | ||
| /// Add a [`ScheduleHook`] to a [`ScheduleLabel`] that triggers before entering the [`Schedule`](super::Schedule). | ||
| pub fn add_enter_hook(&mut self, label: impl ScheduleLabel, hook: ScheduleHook) -> &mut Self { | ||
| self.enter | ||
| .entry(label.intern()) | ||
| .and_modify(|hooks| { | ||
| hooks.push(hook); | ||
| }) | ||
| .or_insert(Vec::from([hook])); | ||
| self | ||
| } | ||
|
|
||
| /// Add a [`ScheduleHook`] to a [`ScheduleLabel`] that triggers after exiting the [`Schedule`](super::Schedule). | ||
| pub fn add_exit_hook(&mut self, label: impl ScheduleLabel, hook: ScheduleHook) -> &mut Self { | ||
| self.exit | ||
| .entry(label.intern()) | ||
| .and_modify(|hooks| { | ||
| hooks.push(hook); | ||
| }) | ||
| .or_insert(Vec::from([hook])); | ||
| self | ||
| } | ||
|
|
||
| /// Execute the [`ScheduleHook`] that runs before a [`ScheduleLabel`]. | ||
| pub fn run_enter(&mut self, world: &mut World, label: impl ScheduleLabel) { | ||
| if let Some(hooks) = self.enter.get_mut(&label.intern()) { | ||
| hooks.retain(|hook| { | ||
| world | ||
| .run_system(hook.clone()) | ||
| .unwrap_or_else(|err| { | ||
| error!( | ||
| "a enter schedule hook fail,schedule label: {:?}, system id:{:?},error context:{:?}", | ||
| label, hook, err | ||
| ); | ||
| ScheduleHookPlan::Clear | ||
| }) | ||
| .eq(&ScheduleHookPlan::Keep) | ||
| }); | ||
| } | ||
| } | ||
|
|
||
| /// Execute the [`ScheduleHook`] that runs after a [`ScheduleLabel`]. | ||
| pub fn run_exit(&mut self, world: &mut World, label: impl ScheduleLabel) { | ||
| if let Some(hooks) = self.exit.get_mut(&label.intern()) { | ||
| hooks.retain(|hook| { | ||
| world | ||
| .run_system(hook.clone()) | ||
| .unwrap_or_else(|err| { | ||
| error!( | ||
| "a exit schedule hook fail,schedule label: {:?}, system id:{:?},error context:{:?}", | ||
| label, hook, err | ||
| ); | ||
| ScheduleHookPlan::Clear | ||
| }) | ||
| .eq(&ScheduleHookPlan::Keep) | ||
| }); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use crate::{ | ||
| prelude::Component, | ||
| system::{Commands, Local}, | ||
| }; | ||
|
|
||
| use super::*; | ||
|
|
||
| #[derive(Debug, ScheduleLabel, Hash, Clone, PartialEq, Eq)] | ||
| pub struct HookLabel; | ||
|
|
||
| #[derive(Debug, Component, PartialEq, Eq)] | ||
| pub struct TestComponent; | ||
|
|
||
| pub const SPAWN_COUNT: usize = 4; | ||
|
|
||
| #[test] | ||
| fn hook_success_run() { | ||
| let mut world = World::new(); | ||
|
|
||
| let system = world.register_system(|mut commands: Commands, mut count: Local<usize>| { | ||
| commands.spawn(TestComponent); | ||
| if *count < SPAWN_COUNT { | ||
| *count += 1; | ||
| ScheduleHookPlan::Keep | ||
| } else { | ||
| ScheduleHookPlan::Clear | ||
| } | ||
| }); | ||
|
|
||
| let mut hooks = ScheduleHooks::default(); | ||
|
|
||
| hooks.add_enter_hook(HookLabel, system); | ||
|
|
||
| for _ in 0..SPAWN_COUNT { | ||
| hooks.run_enter(&mut world, HookLabel); | ||
| } | ||
|
|
||
| let mut query = world.query::<&TestComponent>(); | ||
|
|
||
| let iter = query.iter(&world); | ||
|
|
||
| assert_eq!(SPAWN_COUNT, iter.count()); | ||
|
|
||
| hooks.run_enter(&mut world, HookLabel); | ||
|
|
||
| assert!(hooks | ||
| .enter | ||
| .get(&HookLabel.intern()) | ||
| .is_some_and(|hooks| hooks.is_empty())); | ||
| } | ||
|
|
||
| #[test] | ||
| fn hook_fail_run() { | ||
| let mut world = World::new(); | ||
|
|
||
| let system = world.register_system(|mut commands: Commands| { | ||
| commands.spawn(TestComponent); | ||
| ScheduleHookPlan::Clear | ||
| }); | ||
|
|
||
| let mut hooks = ScheduleHooks::default(); | ||
|
|
||
| hooks.add_enter_hook(HookLabel, system); | ||
|
|
||
| assert_eq!( | ||
| Some(1), | ||
| hooks | ||
| .enter | ||
| .get(&HookLabel.intern()) | ||
| .map(|hooks| hooks.len()) | ||
| ); | ||
|
|
||
| world.despawn(system.entity); | ||
|
|
||
| hooks.run_enter(&mut world, HookLabel); | ||
|
|
||
| assert_eq!( | ||
| Some(0), | ||
| hooks | ||
| .enter | ||
| .get(&HookLabel.intern()) | ||
| .map(|hooks| hooks.len()) | ||
| ); | ||
| } | ||
| } |
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
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why not just trigger an observer instead? Then there's no need to make a whole custom "hooking" thing.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I haven't paid attention to observers for a long time. After completing the rough design, I will give it a try.