Skip to content
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

[Merged by Bors] - Auto-label function systems with SystemTypeIdLabel #4224

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions crates/bevy_ecs/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ pub mod prelude {
system::{
Commands, In, IntoChainSystem, IntoExclusiveSystem, IntoSystem, Local, NonSend,
NonSendMut, Query, QuerySet, RemovedComponents, Res, ResMut, System,
SystemParamFunction,
},
world::{FromWorld, Mut, World},
};
Expand Down
46 changes: 28 additions & 18 deletions crates/bevy_ecs/src/schedule/stage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1583,15 +1583,25 @@ mod tests {
fn ambiguity_detection() {
use super::{find_ambiguities, SystemContainer};

fn find_ambiguities_first_labels(
fn find_ambiguities_first_str_labels(
cart marked this conversation as resolved.
Show resolved Hide resolved
systems: &[impl SystemContainer],
) -> Vec<(BoxedSystemLabel, BoxedSystemLabel)> {
find_ambiguities(systems)
.drain(..)
.map(|(index_a, index_b, _conflicts)| {
(
systems[index_a].labels()[0].clone(),
systems[index_b].labels()[0].clone(),
systems[index_a]
.labels()
.iter()
.find(|a| (&***a).type_id() == std::any::TypeId::of::<&str>())
cart marked this conversation as resolved.
Show resolved Hide resolved
.unwrap()
.clone(),
systems[index_b]
.labels()
.iter()
.find(|a| (&***a).type_id() == std::any::TypeId::of::<&str>())
.unwrap()
.clone(),
)
})
.collect()
Expand Down Expand Up @@ -1621,7 +1631,7 @@ mod tests {
.with_system(component.label("4"));
stage.initialize_systems(&mut world);
stage.rebuild_orders_and_dependencies();
let ambiguities = find_ambiguities_first_labels(&stage.parallel);
let ambiguities = find_ambiguities_first_str_labels(&stage.parallel);
assert!(
ambiguities.contains(&(Box::new("1"), Box::new("4")))
|| ambiguities.contains(&(Box::new("4"), Box::new("1")))
Expand All @@ -1636,7 +1646,7 @@ mod tests {
.with_system(resource.label("4"));
stage.initialize_systems(&mut world);
stage.rebuild_orders_and_dependencies();
let ambiguities = find_ambiguities_first_labels(&stage.parallel);
let ambiguities = find_ambiguities_first_str_labels(&stage.parallel);
assert!(
ambiguities.contains(&(Box::new("1"), Box::new("4")))
|| ambiguities.contains(&(Box::new("4"), Box::new("1")))
Expand All @@ -1661,7 +1671,7 @@ mod tests {
.with_system(resource.label("4"));
stage.initialize_systems(&mut world);
stage.rebuild_orders_and_dependencies();
let ambiguities = find_ambiguities_first_labels(&stage.parallel);
let ambiguities = find_ambiguities_first_str_labels(&stage.parallel);
assert!(
ambiguities.contains(&(Box::new("0"), Box::new("3")))
|| ambiguities.contains(&(Box::new("3"), Box::new("0")))
Expand All @@ -1680,7 +1690,7 @@ mod tests {
.with_system(resource.label("4").in_ambiguity_set("a"));
stage.initialize_systems(&mut world);
stage.rebuild_orders_and_dependencies();
let ambiguities = find_ambiguities_first_labels(&stage.parallel);
let ambiguities = find_ambiguities_first_str_labels(&stage.parallel);
assert!(
ambiguities.contains(&(Box::new("0"), Box::new("3")))
|| ambiguities.contains(&(Box::new("3"), Box::new("0")))
Expand All @@ -1693,7 +1703,7 @@ mod tests {
.with_system(component.label("2"));
stage.initialize_systems(&mut world);
stage.rebuild_orders_and_dependencies();
let ambiguities = find_ambiguities_first_labels(&stage.parallel);
let ambiguities = find_ambiguities_first_str_labels(&stage.parallel);
assert!(
ambiguities.contains(&(Box::new("0"), Box::new("1")))
|| ambiguities.contains(&(Box::new("1"), Box::new("0")))
Expand All @@ -1706,7 +1716,7 @@ mod tests {
.with_system(component.label("2").after("0"));
stage.initialize_systems(&mut world);
stage.rebuild_orders_and_dependencies();
let ambiguities = find_ambiguities_first_labels(&stage.parallel);
let ambiguities = find_ambiguities_first_str_labels(&stage.parallel);
assert!(
ambiguities.contains(&(Box::new("1"), Box::new("2")))
|| ambiguities.contains(&(Box::new("2"), Box::new("1")))
Expand All @@ -1720,7 +1730,7 @@ mod tests {
.with_system(component.label("3").after("1").after("2"));
stage.initialize_systems(&mut world);
stage.rebuild_orders_and_dependencies();
let ambiguities = find_ambiguities_first_labels(&stage.parallel);
let ambiguities = find_ambiguities_first_str_labels(&stage.parallel);
assert!(
ambiguities.contains(&(Box::new("1"), Box::new("2")))
|| ambiguities.contains(&(Box::new("2"), Box::new("1")))
Expand All @@ -1734,7 +1744,7 @@ mod tests {
.with_system(component.label("3").after("1").after("2"));
stage.initialize_systems(&mut world);
stage.rebuild_orders_and_dependencies();
let ambiguities = find_ambiguities_first_labels(&stage.parallel);
let ambiguities = find_ambiguities_first_str_labels(&stage.parallel);
assert_eq!(ambiguities.len(), 0);

let mut stage = SystemStage::parallel()
Expand All @@ -1744,7 +1754,7 @@ mod tests {
.with_system(component.label("3").after("1").after("2"));
stage.initialize_systems(&mut world);
stage.rebuild_orders_and_dependencies();
let ambiguities = find_ambiguities_first_labels(&stage.parallel);
let ambiguities = find_ambiguities_first_str_labels(&stage.parallel);
assert!(
ambiguities.contains(&(Box::new("1"), Box::new("2")))
|| ambiguities.contains(&(Box::new("2"), Box::new("1")))
Expand Down Expand Up @@ -1774,7 +1784,7 @@ mod tests {
);
stage.initialize_systems(&mut world);
stage.rebuild_orders_and_dependencies();
let ambiguities = find_ambiguities_first_labels(&stage.parallel);
let ambiguities = find_ambiguities_first_str_labels(&stage.parallel);
assert!(
ambiguities.contains(&(Box::new("1"), Box::new("2")))
|| ambiguities.contains(&(Box::new("2"), Box::new("1")))
Expand Down Expand Up @@ -1824,7 +1834,7 @@ mod tests {
);
stage.initialize_systems(&mut world);
stage.rebuild_orders_and_dependencies();
let ambiguities = find_ambiguities_first_labels(&stage.parallel);
let ambiguities = find_ambiguities_first_str_labels(&stage.parallel);
assert_eq!(ambiguities.len(), 0);

let mut stage = SystemStage::parallel()
Expand Down Expand Up @@ -1855,7 +1865,7 @@ mod tests {
);
stage.initialize_systems(&mut world);
stage.rebuild_orders_and_dependencies();
let ambiguities = find_ambiguities_first_labels(&stage.parallel);
let ambiguities = find_ambiguities_first_str_labels(&stage.parallel);
assert!(
ambiguities.contains(&(Box::new("1"), Box::new("4")))
|| ambiguities.contains(&(Box::new("4"), Box::new("1")))
Expand Down Expand Up @@ -1889,7 +1899,7 @@ mod tests {
.with_system(empty.exclusive_system().label("6").after("2").after("5"));
stage.initialize_systems(&mut world);
stage.rebuild_orders_and_dependencies();
let ambiguities = find_ambiguities_first_labels(&stage.exclusive_at_start);
let ambiguities = find_ambiguities_first_str_labels(&stage.exclusive_at_start);
assert!(
ambiguities.contains(&(Box::new("1"), Box::new("3")))
|| ambiguities.contains(&(Box::new("3"), Box::new("1")))
Expand Down Expand Up @@ -1926,7 +1936,7 @@ mod tests {
.with_system(empty.exclusive_system().label("6").after("2").after("5"));
stage.initialize_systems(&mut world);
stage.rebuild_orders_and_dependencies();
let ambiguities = find_ambiguities_first_labels(&stage.exclusive_at_start);
let ambiguities = find_ambiguities_first_str_labels(&stage.exclusive_at_start);
assert!(
ambiguities.contains(&(Box::new("2"), Box::new("3")))
|| ambiguities.contains(&(Box::new("3"), Box::new("2")))
Expand All @@ -1952,7 +1962,7 @@ mod tests {
.with_system(empty.exclusive_system().label("3").in_ambiguity_set("a"));
stage.initialize_systems(&mut world);
stage.rebuild_orders_and_dependencies();
let ambiguities = find_ambiguities_first_labels(&stage.exclusive_at_start);
let ambiguities = find_ambiguities_first_str_labels(&stage.exclusive_at_start);
assert_eq!(ambiguities.len(), 0);
}

Expand Down
27 changes: 15 additions & 12 deletions crates/bevy_ecs/src/schedule/system_descriptor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@ use crate::{
AmbiguitySetLabel, BoxedAmbiguitySetLabel, BoxedSystemLabel, IntoRunCriteria,
RunCriteriaDescriptorOrLabel, SystemLabel,
},
system::{BoxedSystem, ExclusiveSystem, ExclusiveSystemCoerced, ExclusiveSystemFn, IntoSystem},
system::{
AsSystemLabel, BoxedSystem, ExclusiveSystem, ExclusiveSystemCoerced, ExclusiveSystemFn,
IntoSystem,
},
};

/// Encapsulates a system and information on when it run in a `SystemStage`.
Expand Down Expand Up @@ -105,9 +108,9 @@ pub struct ParallelSystemDescriptor {

fn new_parallel_descriptor(system: BoxedSystem<(), ()>) -> ParallelSystemDescriptor {
ParallelSystemDescriptor {
labels: system.default_labels(),
system,
run_criteria: None,
labels: Vec::new(),
before: Vec::new(),
after: Vec::new(),
ambiguity_sets: Vec::new(),
Expand All @@ -126,10 +129,10 @@ pub trait ParallelSystemDescriptorCoercion<Params> {
fn label(self, label: impl SystemLabel) -> ParallelSystemDescriptor;

/// Specifies that the system should run before systems with the given label.
fn before(self, label: impl SystemLabel) -> ParallelSystemDescriptor;
fn before<Marker>(self, label: impl AsSystemLabel<Marker>) -> ParallelSystemDescriptor;
cart marked this conversation as resolved.
Show resolved Hide resolved

/// Specifies that the system should run after systems with the given label.
fn after(self, label: impl SystemLabel) -> ParallelSystemDescriptor;
fn after<Marker>(self, label: impl AsSystemLabel<Marker>) -> ParallelSystemDescriptor;

/// Specifies that the system is exempt from execution order ambiguity detection
/// with other systems in this set.
Expand All @@ -150,13 +153,13 @@ impl ParallelSystemDescriptorCoercion<()> for ParallelSystemDescriptor {
self
}

fn before(mut self, label: impl SystemLabel) -> ParallelSystemDescriptor {
self.before.push(Box::new(label));
fn before<Marker>(mut self, label: impl AsSystemLabel<Marker>) -> ParallelSystemDescriptor {
self.before.push(label.as_system_label());
self
}

fn after(mut self, label: impl SystemLabel) -> ParallelSystemDescriptor {
self.after.push(Box::new(label));
fn after<Marker>(mut self, label: impl AsSystemLabel<Marker>) -> ParallelSystemDescriptor {
self.after.push(label.as_system_label());
self
}

Expand All @@ -182,11 +185,11 @@ where
new_parallel_descriptor(Box::new(IntoSystem::into_system(self))).label(label)
}

fn before(self, label: impl SystemLabel) -> ParallelSystemDescriptor {
fn before<Marker>(self, label: impl AsSystemLabel<Marker>) -> ParallelSystemDescriptor {
new_parallel_descriptor(Box::new(IntoSystem::into_system(self))).before(label)
}

fn after(self, label: impl SystemLabel) -> ParallelSystemDescriptor {
fn after<Marker>(self, label: impl AsSystemLabel<Marker>) -> ParallelSystemDescriptor {
new_parallel_descriptor(Box::new(IntoSystem::into_system(self))).after(label)
}

Expand All @@ -207,11 +210,11 @@ impl ParallelSystemDescriptorCoercion<()> for BoxedSystem<(), ()> {
new_parallel_descriptor(self).label(label)
}

fn before(self, label: impl SystemLabel) -> ParallelSystemDescriptor {
fn before<Marker>(self, label: impl AsSystemLabel<Marker>) -> ParallelSystemDescriptor {
new_parallel_descriptor(self).before(label)
}

fn after(self, label: impl SystemLabel) -> ParallelSystemDescriptor {
fn after<Marker>(self, label: impl AsSystemLabel<Marker>) -> ParallelSystemDescriptor {
new_parallel_descriptor(self).after(label)
}

Expand Down
38 changes: 37 additions & 1 deletion crates/bevy_ecs/src/system/function_system.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,19 @@ use crate::{
archetype::{Archetype, ArchetypeComponentId, ArchetypeGeneration, ArchetypeId},
component::ComponentId,
query::{Access, FilteredAccessSet},
schedule::SystemLabel,
system::{
check_system_change_tick, ReadOnlySystemParamFetch, System, SystemParam, SystemParamFetch,
SystemParamState,
},
world::{World, WorldId},
};
use bevy_ecs_macros::all_tuples;
use std::{borrow::Cow, marker::PhantomData};
use std::{
any::{Any, TypeId},
borrow::Cow,
marker::PhantomData,
};

/// The metadata of a [`System`].
pub struct SystemMeta {
Expand Down Expand Up @@ -421,6 +426,19 @@ where
self.system_meta.name.as_ref(),
);
}
fn default_labels(&self) -> Vec<Box<dyn SystemLabel>> {
vec![self.func.as_system_label()]
}
}

#[derive(Debug, Hash, PartialEq, Eq, Copy, Clone)]
/// A [`SystemLabel`] that was automatically generated for a system on the basis of its `TypeId`.
pub struct SystemTypeIdLabel(pub(crate) TypeId);
cart marked this conversation as resolved.
Show resolved Hide resolved
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
pub struct SystemTypeIdLabel(pub(crate) TypeId);
pub(crate) struct SystemTypeIdLabel(pub(crate) TypeId);

Or if we can afford it, remove the pub entirely.

Like #4250. This is more of an implementation detail than anything else, probably shouldn't made public.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Imo this label is a part of our public api (especially with my recent changes, which remove the box from AsSystemLabel). I think there might be cases where this should be accessible to users.


impl SystemLabel for SystemTypeIdLabel {
fn dyn_clone(&self) -> Box<dyn SystemLabel> {
Box::new(*self)
}
}

/// A trait implemented for all functions that can be used as [`System`]s.
Expand Down Expand Up @@ -489,3 +507,21 @@ macro_rules! impl_system_function {
}

all_tuples!(impl_system_function, 0, 16, F);

pub trait AsSystemLabel<Marker> {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add a short doc comment stating this is used for system -> SystemLabel coercion plus a pointer to SystemLabel which illustrates the ergonomics.

It'd also stave off the perpetually missing #[forbid(missing_docs)] for the crate.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good call!

fn as_system_label(&self) -> Box<dyn SystemLabel>;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
fn as_system_label(&self) -> Box<dyn SystemLabel>;
fn as_system_label(this: &Self) -> Box<dyn SystemLabel>;

I don't think we need this to be a method, for similar reasons we don't need the analagous IntoSystem::into_system as a method.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Idk if "non method Self functions" is a pattern I want to encourage generally. We had a good reason to do that for IntoSystem: deprecating .system() let us "encourage" users to use the more ergonomic pattern without outright breaking their code. We don't have that context here. Given that methods are the more common pattern, I think the more relevant question is: why not make this a method?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mostly it's never meant to be used by end users, but will clutter up the flyimport suggests when users are attempting to find .before or .after, especially as alphabetically it is in between those two options.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cluttering auto-complete imports is actually a compelling argument here :)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mostly it's never meant to be used by end users,

I'm not sure I agree, given that getting the "closure" label is something you'd want to do with an as_system_label call (which would benefit from method-style syntax). Other use cases may emerge in the future too (ex: if something needs to accept a list of labels, we can't pass a bunch of different AsSystemLabel impls ... we need to convert to boxed labels before the call).

I personally don't think autocomplete is much of an issue here, as I think most people type at least the first letter of what they're looking for in autocomplete. .b for .before, .a for .after ... .after comes before .as in an alphabetically sorted list.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I personally don't think autocomplete is much of an issue here, as I think most people type at least the first letter of what they're looking for in autocomplete. .b for .before, .a for .after ... .after comes before .as in an alphabetically sorted list.

Fair enough.

}

impl<In, Out, Param: SystemParam, Marker, T: SystemParamFunction<In, Out, Param, Marker>>
AsSystemLabel<(In, Out, Param, Marker)> for T
{
fn as_system_label(&self) -> Box<dyn SystemLabel> {
Box::new(SystemTypeIdLabel(self.type_id()))
}
}

impl<T: SystemLabel> AsSystemLabel<()> for T {
fn as_system_label(&self) -> Box<dyn SystemLabel> {
self.dyn_clone()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The need to clone here is an unfortunate 'regression'

Is there any downside to just making AsSystemLabel consume self?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consuming self would make this unusable for closure systems, as retrieving the label would consume the IntoSystem impl (aka the closure).

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that this doesn't add extra boxing (this replaces the manual boxing that we did in the past). Given that basically all system labels are enums, typeids, or ZSTs, the extra clone probably wouldn't even be measurable, even for many thousands of systems.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's already hugely unergonomic for closure systems though. Either you create the 'same' closure twice:

fn my_closure_system() -> ... {||{}}
app.with_system(my_closure_system()).with_system(other.after(my_closure_system()))

Or you store it in a local variable:

let closure = || {};
with_system(other.after(&closure)).with_system(closure) // has to be this order.

But yeah, perhaps being able to use the second pattern is worthwhile.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IMO this is so challenging (and niche) for closure systems that we shouldn't go out of our way to support it. Providing an explicit label is a nice clear workaround.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems like a really reasonable use case / pattern for closure systems. Given that closure systems are now "the" way to pass in-scope configuration into a system, and closures will also exist in that scope, I think its reasonable to support ordering without needing to define custom labels. At the very least, I think this should be possible (and it currently is):

let closure = || {};
app
  .add_system(foo.after(closure.as_system_label())))
  .add_system(closure)

But I'm also open to making @DJMcNab's second suggestion work.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I just made AsSystemLabel return the actual label type instead of a box. This doesn't "resolve" the extra clone, but it does feel like a cleaner design to me. I really don't think this should consume self, as I don't think we should commit to all system instances being "disposable". "closure systems" already aren't disposable, and things like the current manual FixedTimestep system implementation also "hold state" and shouldn't be disposed of here (I know that the FixedTimestep impl is controversial, but its illustrative of the "custom system" pattern). I stand by the thought that an extra clone here won't hurt anyone, especially when labels are basically exclusively ZSTs and enums.

}
}
5 changes: 5 additions & 0 deletions crates/bevy_ecs/src/system/system.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ use crate::{
archetype::{Archetype, ArchetypeComponentId},
component::ComponentId,
query::Access,
schedule::SystemLabel,
world::World,
};
use std::borrow::Cow;
Expand Down Expand Up @@ -56,6 +57,10 @@ pub trait System: Send + Sync + 'static {
/// Initialize the system.
fn initialize(&mut self, _world: &mut World);
fn check_change_tick(&mut self, change_tick: u32);
/// The default labels for the system
fn default_labels(&self) -> Vec<Box<dyn SystemLabel>> {
cart marked this conversation as resolved.
Show resolved Hide resolved
Vec::new()
}
}

/// A convenience type alias for a boxed [`System`] trait object.
Expand Down
23 changes: 3 additions & 20 deletions examples/ecs/system_sets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,6 @@ struct PostPhysics;
#[derive(Default)]
struct Done(bool);

/// This is used to show that within a [`SystemSet`], individual systems can also
/// be labelled, allowing further fine tuning of run ordering.
#[derive(Clone, Hash, Debug, PartialEq, Eq, SystemLabel)]
pub enum PhysicsSystem {
UpdateVelocity,
Movement,
}

/// This example realizes the following scheme:
///
/// ```none
Expand Down Expand Up @@ -63,18 +55,9 @@ fn main() {
// This criteria ensures this whole system set only runs when this system's
// output says so (ShouldRun::Yes)
.with_run_criteria(run_for_a_second)
.with_system(
update_velocity
// Only applied to the `update_velocity` system
.label(PhysicsSystem::UpdateVelocity),
)
.with_system(
movement
// Only applied to the `movement` system
.label(PhysicsSystem::Movement)
// Enforce order within this system by specifying this
.after(PhysicsSystem::UpdateVelocity),
),
.with_system(update_velocity)
// Make movement run after update_velocity
.with_system(movement.after(update_velocity)),
cart marked this conversation as resolved.
Show resolved Hide resolved
)
.add_system_set(
SystemSet::new()
Expand Down