2023-02-20 18:16:11 +00:00
|
|
|
use std::borrow::Cow;
|
|
|
|
|
|
|
|
use crate::system::{BoxedSystem, CombinatorSystem, Combine, IntoSystem, System};
|
2023-01-17 01:39:17 +00:00
|
|
|
|
|
|
|
pub type BoxedCondition = BoxedSystem<(), bool>;
|
|
|
|
|
|
|
|
/// A system that determines if one or more scheduled systems should run.
|
|
|
|
///
|
|
|
|
/// Implemented for functions and closures that convert into [`System<In=(), Out=bool>`](crate::system::System)
|
|
|
|
/// with [read-only](crate::system::ReadOnlySystemParam) parameters.
|
2023-02-20 18:16:11 +00:00
|
|
|
pub trait Condition<Params>: sealed::Condition<Params> {
|
|
|
|
/// Returns a new run condition that only returns `true`
|
|
|
|
/// if both this one and the passed `and_then` return `true`.
|
|
|
|
///
|
|
|
|
/// The returned run condition is short-circuiting, meaning
|
|
|
|
/// `and_then` will only be invoked if `self` returns `true`.
|
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```should_panic
|
|
|
|
/// use bevy_ecs::prelude::*;
|
|
|
|
///
|
|
|
|
/// #[derive(Resource, PartialEq)]
|
|
|
|
/// struct R(u32);
|
|
|
|
///
|
|
|
|
/// # let mut app = Schedule::new();
|
|
|
|
/// # let mut world = World::new();
|
|
|
|
/// # fn my_system() {}
|
|
|
|
/// app.add_system(
|
|
|
|
/// // The `resource_equals` run condition will panic since we don't initialize `R`,
|
|
|
|
/// // just like if we used `Res<R>` in a system.
|
|
|
|
/// my_system.run_if(resource_equals(R(0))),
|
|
|
|
/// );
|
|
|
|
/// # app.run(&mut world);
|
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// Use `.and_then()` to avoid checking the condition.
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// # use bevy_ecs::prelude::*;
|
|
|
|
/// # #[derive(Resource, PartialEq)]
|
|
|
|
/// # struct R(u32);
|
|
|
|
/// # let mut app = Schedule::new();
|
|
|
|
/// # let mut world = World::new();
|
|
|
|
/// # fn my_system() {}
|
|
|
|
/// app.add_system(
|
|
|
|
/// // `resource_equals` will only get run if the resource `R` exists.
|
|
|
|
/// my_system.run_if(resource_exists::<R>().and_then(resource_equals(R(0)))),
|
|
|
|
/// );
|
|
|
|
/// # app.run(&mut world);
|
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// Note that in this case, it's better to just use the run condition [`resource_exists_and_equals`].
|
|
|
|
///
|
|
|
|
/// [`resource_exists_and_equals`]: common_conditions::resource_exists_and_equals
|
|
|
|
fn and_then<P, C: Condition<P>>(self, and_then: C) -> AndThen<Self::System, C::System> {
|
|
|
|
let a = IntoSystem::into_system(self);
|
|
|
|
let b = IntoSystem::into_system(and_then);
|
|
|
|
let name = format!("{} && {}", a.name(), b.name());
|
|
|
|
CombinatorSystem::new(a, b, Cow::Owned(name))
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns a new run condition that returns `true`
|
|
|
|
/// if either this one or the passed `or_else` return `true`.
|
|
|
|
///
|
|
|
|
/// The returned run condition is short-circuiting, meaning
|
|
|
|
/// `or_else` will only be invoked if `self` returns `false`.
|
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use bevy_ecs::prelude::*;
|
|
|
|
///
|
|
|
|
/// #[derive(Resource, PartialEq)]
|
|
|
|
/// struct A(u32);
|
|
|
|
///
|
|
|
|
/// #[derive(Resource, PartialEq)]
|
|
|
|
/// struct B(u32);
|
|
|
|
///
|
|
|
|
/// # let mut app = Schedule::new();
|
|
|
|
/// # let mut world = World::new();
|
|
|
|
/// # #[derive(Resource)] struct C(bool);
|
|
|
|
/// # fn my_system(mut c: ResMut<C>) { c.0 = true; }
|
|
|
|
/// app.add_system(
|
|
|
|
/// // Only run the system if either `A` or `B` exist.
|
|
|
|
/// my_system.run_if(resource_exists::<A>().or_else(resource_exists::<B>())),
|
|
|
|
/// );
|
|
|
|
/// #
|
|
|
|
/// # world.insert_resource(C(false));
|
|
|
|
/// # app.run(&mut world);
|
|
|
|
/// # assert!(!world.resource::<C>().0);
|
|
|
|
/// #
|
|
|
|
/// # world.insert_resource(A(0));
|
|
|
|
/// # app.run(&mut world);
|
|
|
|
/// # assert!(world.resource::<C>().0);
|
|
|
|
/// #
|
|
|
|
/// # world.remove_resource::<A>();
|
|
|
|
/// # world.insert_resource(B(0));
|
|
|
|
/// # world.insert_resource(C(false));
|
|
|
|
/// # app.run(&mut world);
|
|
|
|
/// # assert!(world.resource::<C>().0);
|
|
|
|
/// ```
|
|
|
|
fn or_else<P, C: Condition<P>>(self, or_else: C) -> OrElse<Self::System, C::System> {
|
|
|
|
let a = IntoSystem::into_system(self);
|
|
|
|
let b = IntoSystem::into_system(or_else);
|
|
|
|
let name = format!("{} || {}", a.name(), b.name());
|
|
|
|
CombinatorSystem::new(a, b, Cow::Owned(name))
|
|
|
|
}
|
|
|
|
}
|
2023-01-17 01:39:17 +00:00
|
|
|
|
|
|
|
impl<Params, F> Condition<Params> for F where F: sealed::Condition<Params> {}
|
|
|
|
|
|
|
|
mod sealed {
|
2023-02-07 22:22:16 +00:00
|
|
|
use crate::system::{IntoSystem, ReadOnlySystem};
|
2023-01-17 01:39:17 +00:00
|
|
|
|
2023-02-16 16:45:48 +00:00
|
|
|
pub trait Condition<Params>:
|
|
|
|
IntoSystem<(), bool, Params, System = Self::ReadOnlySystem>
|
|
|
|
{
|
|
|
|
// This associated type is necessary to let the compiler
|
|
|
|
// know that `Self::System` is `ReadOnlySystem`.
|
|
|
|
type ReadOnlySystem: ReadOnlySystem<In = (), Out = bool>;
|
|
|
|
}
|
2023-01-17 01:39:17 +00:00
|
|
|
|
2023-02-07 22:22:16 +00:00
|
|
|
impl<Params, F> Condition<Params> for F
|
2023-01-17 01:39:17 +00:00
|
|
|
where
|
2023-02-07 22:22:16 +00:00
|
|
|
F: IntoSystem<(), bool, Params>,
|
|
|
|
F::System: ReadOnlySystem,
|
2023-01-17 01:39:17 +00:00
|
|
|
{
|
2023-02-16 16:45:48 +00:00
|
|
|
type ReadOnlySystem = F::System;
|
2023-01-17 01:39:17 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
Migrate engine to Schedule v3 (#7267)
Huge thanks to @maniwani, @devil-ira, @hymm, @cart, @superdump and @jakobhellermann for the help with this PR.
# Objective
- Followup #6587.
- Minimal integration for the Stageless Scheduling RFC: https://github.com/bevyengine/rfcs/pull/45
## Solution
- [x] Remove old scheduling module
- [x] Migrate new methods to no longer use extension methods
- [x] Fix compiler errors
- [x] Fix benchmarks
- [x] Fix examples
- [x] Fix docs
- [x] Fix tests
## Changelog
### Added
- a large number of methods on `App` to work with schedules ergonomically
- the `CoreSchedule` enum
- `App::add_extract_system` via the `RenderingAppExtension` trait extension method
- the private `prepare_view_uniforms` system now has a public system set for scheduling purposes, called `ViewSet::PrepareUniforms`
### Removed
- stages, and all code that mentions stages
- states have been dramatically simplified, and no longer use a stack
- `RunCriteriaLabel`
- `AsSystemLabel` trait
- `on_hierarchy_reports_enabled` run criteria (now just uses an ad hoc resource checking run condition)
- systems in `RenderSet/Stage::Extract` no longer warn when they do not read data from the main world
- `RunCriteriaLabel`
- `transform_propagate_system_set`: this was a nonstandard pattern that didn't actually provide enough control. The systems are already `pub`: the docs have been updated to ensure that the third-party usage is clear.
### Changed
- `System::default_labels` is now `System::default_system_sets`.
- `App::add_default_labels` is now `App::add_default_sets`
- `CoreStage` and `StartupStage` enums are now `CoreSet` and `StartupSet`
- `App::add_system_set` was renamed to `App::add_systems`
- The `StartupSchedule` label is now defined as part of the `CoreSchedules` enum
- `.label(SystemLabel)` is now referred to as `.in_set(SystemSet)`
- `SystemLabel` trait was replaced by `SystemSet`
- `SystemTypeIdLabel<T>` was replaced by `SystemSetType<T>`
- The `ReportHierarchyIssue` resource now has a public constructor (`new`), and implements `PartialEq`
- Fixed time steps now use a schedule (`CoreSchedule::FixedTimeStep`) rather than a run criteria.
- Adding rendering extraction systems now panics rather than silently failing if no subapp with the `RenderApp` label is found.
- the `calculate_bounds` system, with the `CalculateBounds` label, is now in `CoreSet::Update`, rather than in `CoreSet::PostUpdate` before commands are applied.
- `SceneSpawnerSystem` now runs under `CoreSet::Update`, rather than `CoreStage::PreUpdate.at_end()`.
- `bevy_pbr::add_clusters` is no longer an exclusive system
- the top level `bevy_ecs::schedule` module was replaced with `bevy_ecs::scheduling`
- `tick_global_task_pools_on_main_thread` is no longer run as an exclusive system. Instead, it has been replaced by `tick_global_task_pools`, which uses a `NonSend` resource to force running on the main thread.
## Migration Guide
- Calls to `.label(MyLabel)` should be replaced with `.in_set(MySet)`
- Stages have been removed. Replace these with system sets, and then add command flushes using the `apply_system_buffers` exclusive system where needed.
- The `CoreStage`, `StartupStage, `RenderStage` and `AssetStage` enums have been replaced with `CoreSet`, `StartupSet, `RenderSet` and `AssetSet`. The same scheduling guarantees have been preserved.
- Systems are no longer added to `CoreSet::Update` by default. Add systems manually if this behavior is needed, although you should consider adding your game logic systems to `CoreSchedule::FixedTimestep` instead for more reliable framerate-independent behavior.
- Similarly, startup systems are no longer part of `StartupSet::Startup` by default. In most cases, this won't matter to you.
- For example, `add_system_to_stage(CoreStage::PostUpdate, my_system)` should be replaced with
- `add_system(my_system.in_set(CoreSet::PostUpdate)`
- When testing systems or otherwise running them in a headless fashion, simply construct and run a schedule using `Schedule::new()` and `World::run_schedule` rather than constructing stages
- Run criteria have been renamed to run conditions. These can now be combined with each other and with states.
- Looping run criteria and state stacks have been removed. Use an exclusive system that runs a schedule if you need this level of control over system control flow.
- For app-level control flow over which schedules get run when (such as for rollback networking), create your own schedule and insert it under the `CoreSchedule::Outer` label.
- Fixed timesteps are now evaluated in a schedule, rather than controlled via run criteria. The `run_fixed_timestep` system runs this schedule between `CoreSet::First` and `CoreSet::PreUpdate` by default.
- Command flush points introduced by `AssetStage` have been removed. If you were relying on these, add them back manually.
- Adding extract systems is now typically done directly on the main app. Make sure the `RenderingAppExtension` trait is in scope, then call `app.add_extract_system(my_system)`.
- the `calculate_bounds` system, with the `CalculateBounds` label, is now in `CoreSet::Update`, rather than in `CoreSet::PostUpdate` before commands are applied. You may need to order your movement systems to occur before this system in order to avoid system order ambiguities in culling behavior.
- the `RenderLabel` `AppLabel` was renamed to `RenderApp` for clarity
- `App::add_state` now takes 0 arguments: the starting state is set based on the `Default` impl.
- Instead of creating `SystemSet` containers for systems that run in stages, simply use `.on_enter::<State::Variant>()` or its `on_exit` or `on_update` siblings.
- `SystemLabel` derives should be replaced with `SystemSet`. You will also need to add the `Debug`, `PartialEq`, `Eq`, and `Hash` traits to satisfy the new trait bounds.
- `with_run_criteria` has been renamed to `run_if`. Run criteria have been renamed to run conditions for clarity, and should now simply return a bool.
- States have been dramatically simplified: there is no longer a "state stack". To queue a transition to the next state, call `NextState::set`
## TODO
- [x] remove dead methods on App and World
- [x] add `App::add_system_to_schedule` and `App::add_systems_to_schedule`
- [x] avoid adding the default system set at inappropriate times
- [x] remove any accidental cycles in the default plugins schedule
- [x] migrate benchmarks
- [x] expose explicit labels for the built-in command flush points
- [x] migrate engine code
- [x] remove all mentions of stages from the docs
- [x] verify docs for States
- [x] fix uses of exclusive systems that use .end / .at_start / .before_commands
- [x] migrate RenderStage and AssetStage
- [x] migrate examples
- [x] ensure that transform propagation is exported in a sufficiently public way (the systems are already pub)
- [x] ensure that on_enter schedules are run at least once before the main app
- [x] re-enable opt-in to execution order ambiguities
- [x] revert change to `update_bounds` to ensure it runs in `PostUpdate`
- [x] test all examples
- [x] unbreak directional lights
- [x] unbreak shadows (see 3d_scene, 3d_shape, lighting, transparaency_3d examples)
- [x] game menu example shows loading screen and menu simultaneously
- [x] display settings menu is a blank screen
- [x] `without_winit` example panics
- [x] ensure all tests pass
- [x] SubApp doc test fails
- [x] runs_spawn_local tasks fails
- [x] [Fix panic_when_hierachy_cycle test hanging](https://github.com/alice-i-cecile/bevy/pull/120)
## Points of Difficulty and Controversy
**Reviewers, please give feedback on these and look closely**
1. Default sets, from the RFC, have been removed. These added a tremendous amount of implicit complexity and result in hard to debug scheduling errors. They're going to be tackled in the form of "base sets" by @cart in a followup.
2. The outer schedule controls which schedule is run when `App::update` is called.
3. I implemented `Label for `Box<dyn Label>` for our label types. This enables us to store schedule labels in concrete form, and then later run them. I ran into the same set of problems when working with one-shot systems. We've previously investigated this pattern in depth, and it does not appear to lead to extra indirection with nested boxes.
4. `SubApp::update` simply runs the default schedule once. This sucks, but this whole API is incomplete and this was the minimal changeset.
5. `time_system` and `tick_global_task_pools_on_main_thread` no longer use exclusive systems to attempt to force scheduling order
6. Implemetnation strategy for fixed timesteps
7. `AssetStage` was migrated to `AssetSet` without reintroducing command flush points. These did not appear to be used, and it's nice to remove these bottlenecks.
8. Migration of `bevy_render/lib.rs` and pipelined rendering. The logic here is unusually tricky, as we have complex scheduling requirements.
## Future Work (ideally before 0.10)
- Rename schedule_v3 module to schedule or scheduling
- Add a derive macro to states, and likely a `EnumIter` trait of some form
- Figure out what exactly to do with the "systems added should basically work by default" problem
- Improve ergonomics for working with fixed timesteps and states
- Polish FixedTime API to match Time
- Rebase and merge #7415
- Resolve all internal ambiguities (blocked on better tools, especially #7442)
- Add "base sets" to replace the removed default sets.
2023-02-06 02:04:50 +00:00
|
|
|
pub mod common_conditions {
|
2023-02-08 23:24:36 +00:00
|
|
|
use super::Condition;
|
|
|
|
use crate::{
|
|
|
|
schedule::{State, States},
|
|
|
|
system::{In, IntoPipeSystem, ReadOnlySystem, Res, Resource},
|
|
|
|
};
|
2023-01-17 01:39:17 +00:00
|
|
|
|
Migrate engine to Schedule v3 (#7267)
Huge thanks to @maniwani, @devil-ira, @hymm, @cart, @superdump and @jakobhellermann for the help with this PR.
# Objective
- Followup #6587.
- Minimal integration for the Stageless Scheduling RFC: https://github.com/bevyengine/rfcs/pull/45
## Solution
- [x] Remove old scheduling module
- [x] Migrate new methods to no longer use extension methods
- [x] Fix compiler errors
- [x] Fix benchmarks
- [x] Fix examples
- [x] Fix docs
- [x] Fix tests
## Changelog
### Added
- a large number of methods on `App` to work with schedules ergonomically
- the `CoreSchedule` enum
- `App::add_extract_system` via the `RenderingAppExtension` trait extension method
- the private `prepare_view_uniforms` system now has a public system set for scheduling purposes, called `ViewSet::PrepareUniforms`
### Removed
- stages, and all code that mentions stages
- states have been dramatically simplified, and no longer use a stack
- `RunCriteriaLabel`
- `AsSystemLabel` trait
- `on_hierarchy_reports_enabled` run criteria (now just uses an ad hoc resource checking run condition)
- systems in `RenderSet/Stage::Extract` no longer warn when they do not read data from the main world
- `RunCriteriaLabel`
- `transform_propagate_system_set`: this was a nonstandard pattern that didn't actually provide enough control. The systems are already `pub`: the docs have been updated to ensure that the third-party usage is clear.
### Changed
- `System::default_labels` is now `System::default_system_sets`.
- `App::add_default_labels` is now `App::add_default_sets`
- `CoreStage` and `StartupStage` enums are now `CoreSet` and `StartupSet`
- `App::add_system_set` was renamed to `App::add_systems`
- The `StartupSchedule` label is now defined as part of the `CoreSchedules` enum
- `.label(SystemLabel)` is now referred to as `.in_set(SystemSet)`
- `SystemLabel` trait was replaced by `SystemSet`
- `SystemTypeIdLabel<T>` was replaced by `SystemSetType<T>`
- The `ReportHierarchyIssue` resource now has a public constructor (`new`), and implements `PartialEq`
- Fixed time steps now use a schedule (`CoreSchedule::FixedTimeStep`) rather than a run criteria.
- Adding rendering extraction systems now panics rather than silently failing if no subapp with the `RenderApp` label is found.
- the `calculate_bounds` system, with the `CalculateBounds` label, is now in `CoreSet::Update`, rather than in `CoreSet::PostUpdate` before commands are applied.
- `SceneSpawnerSystem` now runs under `CoreSet::Update`, rather than `CoreStage::PreUpdate.at_end()`.
- `bevy_pbr::add_clusters` is no longer an exclusive system
- the top level `bevy_ecs::schedule` module was replaced with `bevy_ecs::scheduling`
- `tick_global_task_pools_on_main_thread` is no longer run as an exclusive system. Instead, it has been replaced by `tick_global_task_pools`, which uses a `NonSend` resource to force running on the main thread.
## Migration Guide
- Calls to `.label(MyLabel)` should be replaced with `.in_set(MySet)`
- Stages have been removed. Replace these with system sets, and then add command flushes using the `apply_system_buffers` exclusive system where needed.
- The `CoreStage`, `StartupStage, `RenderStage` and `AssetStage` enums have been replaced with `CoreSet`, `StartupSet, `RenderSet` and `AssetSet`. The same scheduling guarantees have been preserved.
- Systems are no longer added to `CoreSet::Update` by default. Add systems manually if this behavior is needed, although you should consider adding your game logic systems to `CoreSchedule::FixedTimestep` instead for more reliable framerate-independent behavior.
- Similarly, startup systems are no longer part of `StartupSet::Startup` by default. In most cases, this won't matter to you.
- For example, `add_system_to_stage(CoreStage::PostUpdate, my_system)` should be replaced with
- `add_system(my_system.in_set(CoreSet::PostUpdate)`
- When testing systems or otherwise running them in a headless fashion, simply construct and run a schedule using `Schedule::new()` and `World::run_schedule` rather than constructing stages
- Run criteria have been renamed to run conditions. These can now be combined with each other and with states.
- Looping run criteria and state stacks have been removed. Use an exclusive system that runs a schedule if you need this level of control over system control flow.
- For app-level control flow over which schedules get run when (such as for rollback networking), create your own schedule and insert it under the `CoreSchedule::Outer` label.
- Fixed timesteps are now evaluated in a schedule, rather than controlled via run criteria. The `run_fixed_timestep` system runs this schedule between `CoreSet::First` and `CoreSet::PreUpdate` by default.
- Command flush points introduced by `AssetStage` have been removed. If you were relying on these, add them back manually.
- Adding extract systems is now typically done directly on the main app. Make sure the `RenderingAppExtension` trait is in scope, then call `app.add_extract_system(my_system)`.
- the `calculate_bounds` system, with the `CalculateBounds` label, is now in `CoreSet::Update`, rather than in `CoreSet::PostUpdate` before commands are applied. You may need to order your movement systems to occur before this system in order to avoid system order ambiguities in culling behavior.
- the `RenderLabel` `AppLabel` was renamed to `RenderApp` for clarity
- `App::add_state` now takes 0 arguments: the starting state is set based on the `Default` impl.
- Instead of creating `SystemSet` containers for systems that run in stages, simply use `.on_enter::<State::Variant>()` or its `on_exit` or `on_update` siblings.
- `SystemLabel` derives should be replaced with `SystemSet`. You will also need to add the `Debug`, `PartialEq`, `Eq`, and `Hash` traits to satisfy the new trait bounds.
- `with_run_criteria` has been renamed to `run_if`. Run criteria have been renamed to run conditions for clarity, and should now simply return a bool.
- States have been dramatically simplified: there is no longer a "state stack". To queue a transition to the next state, call `NextState::set`
## TODO
- [x] remove dead methods on App and World
- [x] add `App::add_system_to_schedule` and `App::add_systems_to_schedule`
- [x] avoid adding the default system set at inappropriate times
- [x] remove any accidental cycles in the default plugins schedule
- [x] migrate benchmarks
- [x] expose explicit labels for the built-in command flush points
- [x] migrate engine code
- [x] remove all mentions of stages from the docs
- [x] verify docs for States
- [x] fix uses of exclusive systems that use .end / .at_start / .before_commands
- [x] migrate RenderStage and AssetStage
- [x] migrate examples
- [x] ensure that transform propagation is exported in a sufficiently public way (the systems are already pub)
- [x] ensure that on_enter schedules are run at least once before the main app
- [x] re-enable opt-in to execution order ambiguities
- [x] revert change to `update_bounds` to ensure it runs in `PostUpdate`
- [x] test all examples
- [x] unbreak directional lights
- [x] unbreak shadows (see 3d_scene, 3d_shape, lighting, transparaency_3d examples)
- [x] game menu example shows loading screen and menu simultaneously
- [x] display settings menu is a blank screen
- [x] `without_winit` example panics
- [x] ensure all tests pass
- [x] SubApp doc test fails
- [x] runs_spawn_local tasks fails
- [x] [Fix panic_when_hierachy_cycle test hanging](https://github.com/alice-i-cecile/bevy/pull/120)
## Points of Difficulty and Controversy
**Reviewers, please give feedback on these and look closely**
1. Default sets, from the RFC, have been removed. These added a tremendous amount of implicit complexity and result in hard to debug scheduling errors. They're going to be tackled in the form of "base sets" by @cart in a followup.
2. The outer schedule controls which schedule is run when `App::update` is called.
3. I implemented `Label for `Box<dyn Label>` for our label types. This enables us to store schedule labels in concrete form, and then later run them. I ran into the same set of problems when working with one-shot systems. We've previously investigated this pattern in depth, and it does not appear to lead to extra indirection with nested boxes.
4. `SubApp::update` simply runs the default schedule once. This sucks, but this whole API is incomplete and this was the minimal changeset.
5. `time_system` and `tick_global_task_pools_on_main_thread` no longer use exclusive systems to attempt to force scheduling order
6. Implemetnation strategy for fixed timesteps
7. `AssetStage` was migrated to `AssetSet` without reintroducing command flush points. These did not appear to be used, and it's nice to remove these bottlenecks.
8. Migration of `bevy_render/lib.rs` and pipelined rendering. The logic here is unusually tricky, as we have complex scheduling requirements.
## Future Work (ideally before 0.10)
- Rename schedule_v3 module to schedule or scheduling
- Add a derive macro to states, and likely a `EnumIter` trait of some form
- Figure out what exactly to do with the "systems added should basically work by default" problem
- Improve ergonomics for working with fixed timesteps and states
- Polish FixedTime API to match Time
- Rebase and merge #7415
- Resolve all internal ambiguities (blocked on better tools, especially #7442)
- Add "base sets" to replace the removed default sets.
2023-02-06 02:04:50 +00:00
|
|
|
/// Generates a [`Condition`](super::Condition)-satisfying closure that returns `true`
|
|
|
|
/// if the first time the condition is run and false every time after
|
|
|
|
pub fn run_once() -> impl FnMut() -> bool {
|
|
|
|
let mut has_run = false;
|
|
|
|
move || {
|
|
|
|
if !has_run {
|
|
|
|
has_run = true;
|
|
|
|
true
|
|
|
|
} else {
|
|
|
|
false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-01-17 01:39:17 +00:00
|
|
|
/// Generates a [`Condition`](super::Condition)-satisfying closure that returns `true`
|
|
|
|
/// if the resource exists.
|
|
|
|
pub fn resource_exists<T>() -> impl FnMut(Option<Res<T>>) -> bool
|
|
|
|
where
|
|
|
|
T: Resource,
|
|
|
|
{
|
|
|
|
move |res: Option<Res<T>>| res.is_some()
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Generates a [`Condition`](super::Condition)-satisfying closure that returns `true`
|
|
|
|
/// if the resource is equal to `value`.
|
|
|
|
///
|
|
|
|
/// # Panics
|
|
|
|
///
|
|
|
|
/// The condition will panic if the resource does not exist.
|
|
|
|
pub fn resource_equals<T>(value: T) -> impl FnMut(Res<T>) -> bool
|
|
|
|
where
|
|
|
|
T: Resource + PartialEq,
|
|
|
|
{
|
|
|
|
move |res: Res<T>| *res == value
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Generates a [`Condition`](super::Condition)-satisfying closure that returns `true`
|
|
|
|
/// if the resource exists and is equal to `value`.
|
|
|
|
///
|
|
|
|
/// The condition will return `false` if the resource does not exist.
|
|
|
|
pub fn resource_exists_and_equals<T>(value: T) -> impl FnMut(Option<Res<T>>) -> bool
|
|
|
|
where
|
|
|
|
T: Resource + PartialEq,
|
|
|
|
{
|
|
|
|
move |res: Option<Res<T>>| match res {
|
|
|
|
Some(res) => *res == value,
|
|
|
|
None => false,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Generates a [`Condition`](super::Condition)-satisfying closure that returns `true`
|
|
|
|
/// if the state machine exists.
|
|
|
|
pub fn state_exists<S: States>() -> impl FnMut(Option<Res<State<S>>>) -> bool {
|
|
|
|
move |current_state: Option<Res<State<S>>>| current_state.is_some()
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Generates a [`Condition`](super::Condition)-satisfying closure that returns `true`
|
|
|
|
/// if the state machine is currently in `state`.
|
|
|
|
///
|
|
|
|
/// # Panics
|
|
|
|
///
|
|
|
|
/// The condition will panic if the resource does not exist.
|
2023-02-14 21:30:14 +00:00
|
|
|
pub fn in_state<S: States>(state: S) -> impl FnMut(Res<State<S>>) -> bool {
|
2023-01-17 01:39:17 +00:00
|
|
|
move |current_state: Res<State<S>>| current_state.0 == state
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Generates a [`Condition`](super::Condition)-satisfying closure that returns `true`
|
|
|
|
/// if the state machine exists and is currently in `state`.
|
|
|
|
///
|
|
|
|
/// The condition will return `false` if the state does not exist.
|
|
|
|
pub fn state_exists_and_equals<S: States>(
|
|
|
|
state: S,
|
|
|
|
) -> impl FnMut(Option<Res<State<S>>>) -> bool {
|
|
|
|
move |current_state: Option<Res<State<S>>>| match current_state {
|
|
|
|
Some(current_state) => current_state.0 == state,
|
|
|
|
None => false,
|
|
|
|
}
|
|
|
|
}
|
2023-02-08 23:24:36 +00:00
|
|
|
|
|
|
|
/// Generates a [`Condition`](super::Condition) that inverses the result of passed one.
|
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```
|
|
|
|
/// use bevy_ecs::prelude::*;
|
|
|
|
/// // Building a new schedule/app...
|
|
|
|
/// let mut sched = Schedule::default();
|
|
|
|
/// sched.add_system(
|
|
|
|
/// // This system will never run.
|
|
|
|
/// my_system.run_if(not(always_true))
|
|
|
|
/// )
|
|
|
|
/// // ...
|
|
|
|
/// # ;
|
|
|
|
/// # let mut world = World::new();
|
|
|
|
/// # sched.run(&mut world);
|
|
|
|
///
|
|
|
|
/// // A condition that always returns true.
|
|
|
|
/// fn always_true() -> bool {
|
|
|
|
/// true
|
|
|
|
/// }
|
|
|
|
/// #
|
|
|
|
/// # fn my_system() { unreachable!() }
|
|
|
|
/// ```
|
2023-02-16 16:45:48 +00:00
|
|
|
pub fn not<Params>(
|
|
|
|
condition: impl Condition<Params>,
|
|
|
|
) -> impl ReadOnlySystem<In = (), Out = bool> {
|
2023-02-08 23:24:36 +00:00
|
|
|
condition.pipe(|In(val): In<bool>| !val)
|
|
|
|
}
|
2023-01-17 01:39:17 +00:00
|
|
|
}
|
2023-02-20 18:16:11 +00:00
|
|
|
|
|
|
|
/// Combines the outputs of two systems using the `&&` operator.
|
|
|
|
pub type AndThen<A, B> = CombinatorSystem<AndThenMarker, A, B>;
|
|
|
|
|
|
|
|
/// Combines the outputs of two systems using the `||` operator.
|
|
|
|
pub type OrElse<A, B> = CombinatorSystem<OrElseMarker, A, B>;
|
|
|
|
|
|
|
|
#[doc(hidden)]
|
|
|
|
pub struct AndThenMarker;
|
|
|
|
|
|
|
|
impl<In, A, B> Combine<A, B> for AndThenMarker
|
|
|
|
where
|
|
|
|
In: Copy,
|
|
|
|
A: System<In = In, Out = bool>,
|
|
|
|
B: System<In = In, Out = bool>,
|
|
|
|
{
|
|
|
|
type In = In;
|
|
|
|
type Out = bool;
|
|
|
|
|
|
|
|
fn combine(
|
|
|
|
input: Self::In,
|
|
|
|
a: impl FnOnce(<A as System>::In) -> <A as System>::Out,
|
|
|
|
b: impl FnOnce(<B as System>::In) -> <B as System>::Out,
|
|
|
|
) -> Self::Out {
|
|
|
|
a(input) && b(input)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[doc(hidden)]
|
|
|
|
pub struct OrElseMarker;
|
|
|
|
|
|
|
|
impl<In, A, B> Combine<A, B> for OrElseMarker
|
|
|
|
where
|
|
|
|
In: Copy,
|
|
|
|
A: System<In = In, Out = bool>,
|
|
|
|
B: System<In = In, Out = bool>,
|
|
|
|
{
|
|
|
|
type In = In;
|
|
|
|
type Out = bool;
|
|
|
|
|
|
|
|
fn combine(
|
|
|
|
input: Self::In,
|
|
|
|
a: impl FnOnce(<A as System>::In) -> <A as System>::Out,
|
|
|
|
b: impl FnOnce(<B as System>::In) -> <B as System>::Out,
|
|
|
|
) -> Self::Out {
|
|
|
|
a(input) || b(input)
|
|
|
|
}
|
|
|
|
}
|