From a4c621a127bebac0c6d8e870521f4b351b0ab7b5 Mon Sep 17 00:00:00 2001 From: Joseph <21144246+JoJoJet@users.noreply.github.com> Date: Wed, 26 Jun 2024 05:47:46 -0700 Subject: [PATCH] Use an opaque type for `EntityCommand::with_entity` (#11210) # Objective The trait method `with_entity` is used to add an `EntityCommand` to the command queue. Currently this method returns `WithEntity` which pairs a command with an `Entity`. By replacing this explicit type with an opaque type, implementors can override this default implementation by returning a custom command or closure that does the same thing with a lower memory footprint. # Solution Return an opaque type from the method. As a bonus this file is now cleaner without the `WithEntity` boilerplate --- crates/bevy_ecs/src/system/commands/mod.rs | 34 ++++++---------------- 1 file changed, 9 insertions(+), 25 deletions(-) diff --git a/crates/bevy_ecs/src/system/commands/mod.rs b/crates/bevy_ecs/src/system/commands/mod.rs index 15e4861fe0..d8d2914187 100644 --- a/crates/bevy_ecs/src/system/commands/mod.rs +++ b/crates/bevy_ecs/src/system/commands/mod.rs @@ -14,7 +14,6 @@ use crate::{ }; use bevy_utils::tracing::{error, info}; pub use parallel_scope::*; -use std::marker::PhantomData; /// A [`Command`] queue to perform structural changes to the [`World`]. /// @@ -825,34 +824,19 @@ impl<'w, 's> Commands<'w, 's> { /// ``` pub trait EntityCommand: Send + 'static { /// Executes this command for the given [`Entity`]. - fn apply(self, id: Entity, world: &mut World); + fn apply(self, entity: Entity, world: &mut World); + /// Returns a [`Command`] which executes this [`EntityCommand`] for the given [`Entity`]. - fn with_entity(self, id: Entity) -> WithEntity + /// + /// This method is called when adding an [`EntityCommand`] to a command queue via [`Commands`]. + /// You can override the provided implementation if you can return a `Command` with a smaller memory + /// footprint than `(Entity, Self)`. + /// In most cases the provided implementation is sufficient. + fn with_entity(self, entity: Entity) -> impl Command where Self: Sized, { - WithEntity { - cmd: self, - id, - marker: PhantomData, - } - } -} - -/// Turns an [`EntityCommand`] type into a [`Command`] type. -pub struct WithEntity> { - cmd: C, - id: Entity, - marker: PhantomData Marker>, -} - -impl> Command for WithEntity -where - M: 'static, -{ - #[inline] - fn apply(self, world: &mut World) { - self.cmd.apply(self.id, world); + move |world: &mut World| self.apply(entity, world) } }