Revert "Have EntityCommands methods consume self for easier chaining" (#15523)

As discussed in #15521

- Partial revert of #14897, reverting the change to the methods to
consume `self`
- The `insert_if` method is kept

The migration guide of #14897 should be removed
Closes #15521

---------

Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
This commit is contained in:
Tim 2024-10-02 12:47:26 +00:00 committed by GitHub
parent 23b0dd6ffd
commit 461305b3d7
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
22 changed files with 104 additions and 106 deletions

View file

@ -43,8 +43,8 @@ pub fn spawn_commands(criterion: &mut Criterion) {
bencher.iter(|| {
let mut commands = Commands::new(&mut command_queue, &world);
for i in 0..entity_count {
let entity = commands
.spawn_empty()
let mut entity = commands.spawn_empty();
entity
.insert_if(A, || black_box(i % 2 == 0))
.insert_if(B, || black_box(i % 3 == 0))
.insert_if(C, || black_box(i % 4 == 0));

View file

@ -390,7 +390,9 @@ impl<'w, 's> Commands<'w, 's> {
/// - [`spawn_batch`](Self::spawn_batch) to spawn entities with a bundle each.
#[track_caller]
pub fn spawn<T: Bundle>(&mut self, bundle: T) -> EntityCommands {
self.spawn_empty().insert(bundle)
let mut entity = self.spawn_empty();
entity.insert(bundle);
entity
}
/// Returns the [`EntityCommands`] for the requested [`Entity`].
@ -1043,7 +1045,7 @@ impl EntityCommands<'_> {
/// # bevy_ecs::system::assert_is_system(add_combat_stats_system);
/// ```
#[track_caller]
pub fn insert(self, bundle: impl Bundle) -> Self {
pub fn insert(&mut self, bundle: impl Bundle) -> &mut Self {
self.queue(insert(bundle, InsertMode::Replace))
}
@ -1077,7 +1079,7 @@ impl EntityCommands<'_> {
/// # bevy_ecs::system::assert_is_system(add_health_system);
/// ```
#[track_caller]
pub fn insert_if<F>(self, bundle: impl Bundle, condition: F) -> Self
pub fn insert_if<F>(&mut self, bundle: impl Bundle, condition: F) -> &mut Self
where
F: FnOnce() -> bool,
{
@ -1102,7 +1104,7 @@ impl EntityCommands<'_> {
/// The command will panic when applied if the associated entity does not exist.
///
/// To avoid a panic in this case, use the command [`Self::try_insert_if_new`] instead.
pub fn insert_if_new(self, bundle: impl Bundle) -> Self {
pub fn insert_if_new(&mut self, bundle: impl Bundle) -> &mut Self {
self.queue(insert(bundle, InsertMode::Keep))
}
@ -1120,7 +1122,7 @@ impl EntityCommands<'_> {
///
/// To avoid a panic in this case, use the command [`Self::try_insert_if_new`]
/// instead.
pub fn insert_if_new_and<F>(self, bundle: impl Bundle, condition: F) -> Self
pub fn insert_if_new_and<F>(&mut self, bundle: impl Bundle, condition: F) -> &mut Self
where
F: FnOnce() -> bool,
{
@ -1147,10 +1149,10 @@ impl EntityCommands<'_> {
/// - `T` must have the same layout as the one passed during `component_id` creation.
#[track_caller]
pub unsafe fn insert_by_id<T: Send + 'static>(
self,
&mut self,
component_id: ComponentId,
value: T,
) -> Self {
) -> &mut Self {
let caller = Location::caller();
// SAFETY: same invariants as parent call
self.queue(unsafe {insert_by_id(component_id, value, move |entity| {
@ -1167,10 +1169,10 @@ impl EntityCommands<'_> {
/// - [`ComponentId`] must be from the same world as `self`.
/// - `T` must have the same layout as the one passed during `component_id` creation.
pub unsafe fn try_insert_by_id<T: Send + 'static>(
self,
&mut self,
component_id: ComponentId,
value: T,
) -> Self {
) -> &mut Self {
// SAFETY: same invariants as parent call
self.queue(unsafe { insert_by_id(component_id, value, |_| {}) })
}
@ -1224,7 +1226,7 @@ impl EntityCommands<'_> {
/// # bevy_ecs::system::assert_is_system(add_combat_stats_system);
/// ```
#[track_caller]
pub fn try_insert(self, bundle: impl Bundle) -> Self {
pub fn try_insert(&mut self, bundle: impl Bundle) -> &mut Self {
self.queue(try_insert(bundle, InsertMode::Replace))
}
@ -1255,7 +1257,7 @@ impl EntityCommands<'_> {
/// # bevy_ecs::system::assert_is_system(add_health_system);
/// ```
#[track_caller]
pub fn try_insert_if<F>(self, bundle: impl Bundle, condition: F) -> Self
pub fn try_insert_if<F>(&mut self, bundle: impl Bundle, condition: F) -> &mut Self
where
F: FnOnce() -> bool,
{
@ -1301,7 +1303,7 @@ impl EntityCommands<'_> {
/// }
/// # bevy_ecs::system::assert_is_system(add_health_system);
/// ```
pub fn try_insert_if_new_and<F>(self, bundle: impl Bundle, condition: F) -> Self
pub fn try_insert_if_new_and<F>(&mut self, bundle: impl Bundle, condition: F) -> &mut Self
where
F: FnOnce() -> bool,
{
@ -1321,7 +1323,7 @@ impl EntityCommands<'_> {
/// # Note
///
/// Unlike [`Self::insert_if_new`], this will not panic if the associated entity does not exist.
pub fn try_insert_if_new(self, bundle: impl Bundle) -> Self {
pub fn try_insert_if_new(&mut self, bundle: impl Bundle) -> &mut Self {
self.queue(try_insert(bundle, InsertMode::Keep))
}
@ -1360,7 +1362,7 @@ impl EntityCommands<'_> {
/// }
/// # bevy_ecs::system::assert_is_system(remove_combat_stats_system);
/// ```
pub fn remove<T>(self) -> Self
pub fn remove<T>(&mut self) -> &mut Self
where
T: Bundle,
{
@ -1368,12 +1370,12 @@ impl EntityCommands<'_> {
}
/// Removes a component from the entity.
pub fn remove_by_id(self, component_id: ComponentId) -> Self {
pub fn remove_by_id(&mut self, component_id: ComponentId) -> &mut Self {
self.queue(remove_by_id(component_id))
}
/// Removes all components associated with the entity.
pub fn clear(self) -> Self {
pub fn clear(&mut self) -> &mut Self {
self.queue(clear())
}
@ -1405,8 +1407,8 @@ impl EntityCommands<'_> {
/// # bevy_ecs::system::assert_is_system(remove_character_system);
/// ```
#[track_caller]
pub fn despawn(self) -> Self {
self.queue(despawn())
pub fn despawn(&mut self) {
self.queue(despawn());
}
/// Pushes an [`EntityCommand`] to the queue, which will get executed for the current [`Entity`].
@ -1425,8 +1427,7 @@ impl EntityCommands<'_> {
/// # }
/// # bevy_ecs::system::assert_is_system(my_system);
/// ```
#[allow(clippy::should_implement_trait)]
pub fn queue<M: 'static>(mut self, command: impl EntityCommand<M>) -> Self {
pub fn queue<M: 'static>(&mut self, command: impl EntityCommand<M>) -> &mut Self {
self.commands.queue(command.with_entity(self.entity));
self
}
@ -1468,7 +1469,7 @@ impl EntityCommands<'_> {
/// }
/// # bevy_ecs::system::assert_is_system(remove_combat_stats_system);
/// ```
pub fn retain<T>(self) -> Self
pub fn retain<T>(&mut self) -> &mut Self
where
T: Bundle,
{
@ -1480,7 +1481,7 @@ impl EntityCommands<'_> {
/// # Panics
///
/// The command will panic when applied if the associated entity does not exist.
pub fn log_components(self) -> Self {
pub fn log_components(&mut self) -> &mut Self {
self.queue(log_components)
}
@ -1493,13 +1494,16 @@ impl EntityCommands<'_> {
/// watches this entity.
///
/// [`Trigger`]: crate::observer::Trigger
pub fn trigger(mut self, event: impl Event) -> Self {
pub fn trigger(&mut self, event: impl Event) -> &mut Self {
self.commands.trigger_targets(event, self.entity);
self
}
/// Creates an [`Observer`] listening for a trigger of type `T` that targets this entity.
pub fn observe<E: Event, B: Bundle, M>(self, system: impl IntoObserverSystem<E, B, M>) -> Self {
pub fn observe<E: Event, B: Bundle, M>(
&mut self,
system: impl IntoObserverSystem<E, B, M>,
) -> &mut Self {
self.queue(observe(system))
}
}
@ -1512,9 +1516,8 @@ pub struct EntityEntryCommands<'a, T> {
impl<'a, T: Component> EntityEntryCommands<'a, T> {
/// Modify the component `T` if it exists, using the the function `modify`.
pub fn and_modify(mut self, modify: impl FnOnce(Mut<T>) + Send + Sync + 'static) -> Self {
self.entity_commands = self
.entity_commands
pub fn and_modify(&mut self, modify: impl FnOnce(Mut<T>) + Send + Sync + 'static) -> &mut Self {
self.entity_commands
.queue(move |mut entity: EntityWorldMut| {
if let Some(value) = entity.get_mut() {
modify(value);
@ -1532,9 +1535,8 @@ impl<'a, T: Component> EntityEntryCommands<'a, T> {
/// Panics if the entity does not exist.
/// See [`or_try_insert`](Self::or_try_insert) for a non-panicking version.
#[track_caller]
pub fn or_insert(mut self, default: T) -> Self {
self.entity_commands = self
.entity_commands
pub fn or_insert(&mut self, default: T) -> &mut Self {
self.entity_commands
.queue(insert(default, InsertMode::Keep));
self
}
@ -1545,9 +1547,8 @@ impl<'a, T: Component> EntityEntryCommands<'a, T> {
///
/// See also [`or_insert_with`](Self::or_insert_with).
#[track_caller]
pub fn or_try_insert(mut self, default: T) -> Self {
self.entity_commands = self
.entity_commands
pub fn or_try_insert(&mut self, default: T) -> &mut Self {
self.entity_commands
.queue(try_insert(default, InsertMode::Keep));
self
}
@ -1561,7 +1562,7 @@ impl<'a, T: Component> EntityEntryCommands<'a, T> {
/// Panics if the entity does not exist.
/// See [`or_try_insert_with`](Self::or_try_insert_with) for a non-panicking version.
#[track_caller]
pub fn or_insert_with(self, default: impl Fn() -> T) -> Self {
pub fn or_insert_with(&mut self, default: impl Fn() -> T) -> &mut Self {
self.or_insert(default())
}
@ -1571,7 +1572,7 @@ impl<'a, T: Component> EntityEntryCommands<'a, T> {
///
/// See also [`or_insert`](Self::or_insert) and [`or_try_insert`](Self::or_try_insert).
#[track_caller]
pub fn or_try_insert_with(self, default: impl Fn() -> T) -> Self {
pub fn or_try_insert_with(&mut self, default: impl Fn() -> T) -> &mut Self {
self.or_try_insert(default())
}
@ -1583,7 +1584,7 @@ impl<'a, T: Component> EntityEntryCommands<'a, T> {
///
/// Panics if the entity does not exist.
#[track_caller]
pub fn or_default(self) -> Self
pub fn or_default(&mut self) -> &mut Self
where
T: Default,
{
@ -1600,12 +1601,11 @@ impl<'a, T: Component> EntityEntryCommands<'a, T> {
///
/// Panics if the entity does not exist.
#[track_caller]
pub fn or_from_world(mut self) -> Self
pub fn or_from_world(&mut self) -> &mut Self
where
T: FromWorld,
{
self.entity_commands = self
.entity_commands
self.entity_commands
.queue(insert_from_world::<T>(InsertMode::Keep));
self
}

View file

@ -1345,7 +1345,7 @@ pub fn gamepad_connection_system(
let id = connection_event.gamepad;
match &connection_event.connection {
GamepadConnection::Connected(info) => {
let Some(gamepad) = commands.get_entity(id) else {
let Some(mut gamepad) = commands.get_entity(id) else {
warn!("Gamepad {:} removed before handling connection event.", id);
continue;
};
@ -1353,7 +1353,7 @@ pub fn gamepad_connection_system(
info!("Gamepad {:?} connected.", id);
}
GamepadConnection::Disconnected => {
let Some(gamepad) = commands.get_entity(id) else {
let Some(mut gamepad) = commands.get_entity(id) else {
warn!("Gamepad {:} removed before handling disconnection event. You can ignore this if you manually removed it.", id);
continue;
};

View file

@ -585,7 +585,7 @@ pub fn extract_camera_previous_view_data(
for (entity, camera, maybe_previous_view_data) in cameras_3d.iter() {
if camera.is_active {
let entity = entity.id();
let entity = commands.get_or_spawn(entity);
let mut entity = commands.get_or_spawn(entity);
if let Some(previous_view_data) = maybe_previous_view_data {
entity.insert(previous_view_data.clone());

View file

@ -435,9 +435,9 @@ pub(crate) fn add_light_view_entities(
trigger: Trigger<OnAdd, (ExtractedDirectionalLight, ExtractedPointLight)>,
mut commands: Commands,
) {
commands
.get_entity(trigger.entity())
.map(|v| v.insert(LightViewEntities::default()));
if let Some(mut v) = commands.get_entity(trigger.entity()) {
v.insert(LightViewEntities::default());
}
}
pub(crate) fn remove_light_view_entities(
@ -447,7 +447,7 @@ pub(crate) fn remove_light_view_entities(
) {
if let Ok(entities) = query.get(trigger.entity()) {
for e in entities.0.iter().copied() {
if let Some(v) = commands.get_entity(e) {
if let Some(mut v) = commands.get_entity(e) {
v.despawn();
}
}

View file

@ -156,7 +156,7 @@ fn apply_wireframe_material(
global_material: Res<GlobalWireframeMaterial>,
) {
for e in removed_wireframes.read().chain(no_wireframes.iter()) {
if let Some(commands) = commands.get_entity(e) {
if let Some(mut commands) = commands.get_entity(e) {
commands.remove::<MeshMaterial3d<WireframeMaterial>>();
}
}

View file

@ -244,7 +244,7 @@ pub fn update_interactions(
for (hovered_entity, new_interaction) in new_interaction_state.drain() {
if let Ok(mut interaction) = interact.get_mut(hovered_entity) {
*interaction = new_interaction;
} else if let Some(entity_commands) = commands.get_entity(hovered_entity) {
} else if let Some(mut entity_commands) = commands.get_entity(hovered_entity) {
entity_commands.try_insert(new_interaction);
}
}

View file

@ -1051,7 +1051,7 @@ pub fn extract_cameras(
}
let mut commands = commands.entity(render_entity.id());
commands = commands.insert((
commands.insert((
ExtractedCamera {
target: camera.target.normalize(primary_window),
viewport: camera.viewport.clone(),
@ -1087,15 +1087,15 @@ pub fn extract_cameras(
));
if let Some(temporal_jitter) = temporal_jitter {
commands = commands.insert(temporal_jitter.clone());
commands.insert(temporal_jitter.clone());
}
if let Some(render_layers) = render_layers {
commands = commands.insert(render_layers.clone());
commands.insert(render_layers.clone());
}
if let Some(perspective) = projection {
commands = commands.insert(perspective.clone());
commands.insert(perspective.clone());
}
if gpu_culling {
if *gpu_preprocessing_support == GpuPreprocessingSupport::Culling {

View file

@ -162,7 +162,7 @@ fn apply_wireframe_material(
global_material: Res<GlobalWireframe2dMaterial>,
) {
for e in removed_wireframes.read().chain(no_wireframes.iter()) {
if let Some(commands) = commands.get_entity(e) {
if let Some(mut commands) = commands.get_entity(e) {
commands.remove::<MeshMaterial2d<Wireframe2dMaterial>>();
}
}

View file

@ -510,9 +510,8 @@ pub fn extract_default_ui_camera_view(
TemporaryRenderEntity,
))
.id();
let entity_commands = commands
.get_or_spawn(entity)
.insert(DefaultCameraView(default_camera_view));
let mut entity_commands = commands.get_or_spawn(entity);
entity_commands.insert(DefaultCameraView(default_camera_view));
if let Some(ui_anti_alias) = ui_anti_alias {
entity_commands.insert(*ui_anti_alias);
}

View file

@ -83,7 +83,7 @@ fn spawn_sprites(
..default()
});
if let Some(scale_mode) = scale_mode {
cmd = cmd.insert(scale_mode);
cmd.insert(scale_mode);
}
cmd.with_children(|builder| {
builder.spawn(Text2dBundle {

View file

@ -55,7 +55,7 @@ fn modify_aa(
// No AA
if keys.just_pressed(KeyCode::Digit1) {
*msaa = Msaa::Off;
camera = camera
camera
.remove::<Fxaa>()
.remove::<Smaa>()
.remove::<TaaComponents>();
@ -63,7 +63,7 @@ fn modify_aa(
// MSAA
if keys.just_pressed(KeyCode::Digit2) && *msaa == Msaa::Off {
camera = camera
camera
.remove::<Fxaa>()
.remove::<Smaa>()
.remove::<TaaComponents>();
@ -87,7 +87,7 @@ fn modify_aa(
// FXAA
if keys.just_pressed(KeyCode::Digit3) && fxaa.is_none() {
*msaa = Msaa::Off;
camera = camera
camera
.remove::<Smaa>()
.remove::<TaaComponents>()
.insert(Fxaa::default());
@ -120,7 +120,7 @@ fn modify_aa(
// SMAA
if keys.just_pressed(KeyCode::Digit4) && smaa.is_none() {
*msaa = Msaa::Off;
camera = camera
camera
.remove::<Fxaa>()
.remove::<TaaComponents>()
.insert(Smaa::default());

View file

@ -70,17 +70,16 @@ fn main() {
fn setup(mut commands: Commands, asset_server: Res<AssetServer>, app_settings: Res<AppSettings>) {
// Spawn the camera. Enable HDR and bloom, as that highlights the depth of
// field effect.
let camera = commands
.spawn(Camera3dBundle {
transform: Transform::from_xyz(0.0, 4.5, 8.25).looking_at(Vec3::ZERO, Vec3::Y),
camera: Camera {
hdr: true,
..default()
},
tonemapping: Tonemapping::TonyMcMapface,
let mut camera = commands.spawn(Camera3dBundle {
transform: Transform::from_xyz(0.0, 4.5, 8.25).looking_at(Vec3::ZERO, Vec3::Y),
camera: Camera {
hdr: true,
..default()
})
.insert(Bloom::NATURAL);
},
tonemapping: Tonemapping::TonyMcMapface,
..default()
});
camera.insert(Bloom::NATURAL);
// Insert the depth of field settings.
if let Some(depth_of_field) = Option::<DepthOfField>::from(*app_settings) {

View file

@ -135,35 +135,35 @@ fn spawn_cars(
for i in 0..N_CARS {
let color = colors[i % colors.len()].clone();
let mut entity = commands
commands
.spawn((
Mesh3d(box_mesh.clone()),
MeshMaterial3d(color.clone()),
Transform::from_scale(Vec3::splat(0.5)),
Moves(i as f32 * 2.0),
))
.insert_if(CameraTracked, || i == 0);
entity.with_children(|parent| {
parent.spawn((
Mesh3d(box_mesh.clone()),
MeshMaterial3d(color),
Transform::from_xyz(0.0, 0.08, 0.03).with_scale(Vec3::new(1.0, 1.0, 0.5)),
));
let mut spawn_wheel = |x: f32, z: f32| {
.insert_if(CameraTracked, || i == 0)
.with_children(|parent| {
parent.spawn((
Mesh3d(cylinder.clone()),
MeshMaterial3d(wheel_matl.clone()),
Transform::from_xyz(0.14 * x, -0.045, 0.15 * z)
.with_scale(Vec3::new(0.15, 0.04, 0.15))
.with_rotation(Quat::from_rotation_z(std::f32::consts::FRAC_PI_2)),
Rotates,
Mesh3d(box_mesh.clone()),
MeshMaterial3d(color),
Transform::from_xyz(0.0, 0.08, 0.03).with_scale(Vec3::new(1.0, 1.0, 0.5)),
));
};
spawn_wheel(1.0, 1.0);
spawn_wheel(1.0, -1.0);
spawn_wheel(-1.0, 1.0);
spawn_wheel(-1.0, -1.0);
});
let mut spawn_wheel = |x: f32, z: f32| {
parent.spawn((
Mesh3d(cylinder.clone()),
MeshMaterial3d(wheel_matl.clone()),
Transform::from_xyz(0.14 * x, -0.045, 0.15 * z)
.with_scale(Vec3::new(0.15, 0.04, 0.15))
.with_rotation(Quat::from_rotation_z(std::f32::consts::FRAC_PI_2)),
Rotates,
));
};
spawn_wheel(1.0, 1.0);
spawn_wheel(1.0, -1.0);
spawn_wheel(-1.0, 1.0);
spawn_wheel(-1.0, -1.0);
});
}
}

View file

@ -292,8 +292,8 @@ fn handle_light_type_change(
app_status.light_type = light_type;
for light in lights.iter_mut() {
let light_commands = commands
.entity(light)
let mut light_commands = commands.entity(light);
light_commands
.remove::<DirectionalLight>()
.remove::<PointLight>()
.remove::<SpotLight>();

View file

@ -110,8 +110,8 @@ fn update(
let (camera_entity, ssao, temporal_jitter) = camera.single();
let mut commands = commands
.entity(camera_entity)
let mut commands = commands.entity(camera_entity);
commands
.insert_if(
ScreenSpaceAmbientOcclusion {
quality_level: ScreenSpaceAmbientOcclusionQualityLevel::Low,
@ -137,7 +137,7 @@ fn update(
|| keycode.just_pressed(KeyCode::Digit5),
);
if keycode.just_pressed(KeyCode::Digit1) {
commands = commands.remove::<ScreenSpaceAmbientOcclusion>();
commands.remove::<ScreenSpaceAmbientOcclusion>();
}
if keycode.just_pressed(KeyCode::Space) {
if temporal_jitter.is_some() {

View file

@ -307,7 +307,7 @@ fn setup_node_rects(commands: &mut Commands) {
));
if let NodeType::Clip(ref clip) = node_type {
container = container.insert((
container.insert((
Interaction::None,
RelativeCursorPosition::default(),
(*clip).clone(),

View file

@ -149,7 +149,7 @@ fn on_remove_mine(
fn explode_mine(trigger: Trigger<Explode>, query: Query<&Mine>, mut commands: Commands) {
// If a triggered event is targeting a specific entity you can access it with `.entity()`
let id = trigger.entity();
let Some(entity) = commands.get_entity(id) else {
let Some(mut entity) = commands.get_entity(id) else {
return;
};
info!("Boom! {:?} exploded.", id.index());

View file

@ -743,7 +743,7 @@ mod menu {
button_text_style.clone(),
));
for volume_setting in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] {
let entity = parent.spawn((
let mut entity = parent.spawn((
ButtonBundle {
style: Style {
width: Val::Px(30.0),

View file

@ -257,7 +257,7 @@ fn spawn_button(
));
if let Some(image) = image {
builder = builder.insert(UiImage::new(image));
builder.insert(UiImage::new(image));
}
if spawn_text {

View file

@ -177,7 +177,7 @@ fn setup(
// camera
let mut camera = commands.spawn(Camera3dBundle::default());
if args.gpu_culling {
camera = camera.insert(GpuCulling);
camera.insert(GpuCulling);
}
if args.no_cpu_culling {
camera.insert(NoCpuCulling);

View file

@ -413,7 +413,7 @@ fn spawn_tree(
&& (depth >= update_filter.min_depth && depth <= update_filter.max_depth);
if update {
cmd = cmd.insert(UpdateValue(sep));
cmd.insert(UpdateValue(sep));
result.active_nodes += 1;
}
@ -426,7 +426,7 @@ fn spawn_tree(
};
// only insert the components necessary for the transform propagation
cmd = cmd.insert(transform);
cmd.insert(transform);
cmd.id()
};