Skip to content

Commit 3c8fae2

Browse files
carteugineerdalice-i-cecile
authored
Improved Entity Mapping and Cloning (#17687)
Fixes #17535 Bevy's approach to handling "entity mapping" during spawning and cloning needs some work. The addition of [Relations](#17398) both [introduced a new "duplicate entities" bug when spawning scenes in the scene system](#17535) and made the weaknesses of the current mapping system exceedingly clear: 1. Entity mapping requires _a ton_ of boilerplate (implement or derive VisitEntities and VisitEntitesMut, then register / reflect MapEntities). Knowing the incantation is challenging and if you forget to do it in part or in whole, spawning subtly breaks. 2. Entity mapping a spawned component in scenes incurs unnecessary overhead: look up ReflectMapEntities, create a _brand new temporary instance_ of the component using FromReflect, map the entities in that instance, and then apply that on top of the actual component using reflection. We can do much better. Additionally, while our new [Entity cloning system](#16132) is already pretty great, it has some areas we can make better: * It doesn't expose semantic info about the clone (ex: ignore or "clone empty"), meaning we can't key off of that in places where it would be useful, such as scene spawning. Rather than duplicating this info across contexts, I think it makes more sense to add that info to the clone system, especially given that we'd like to use cloning code in some of our spawning scenarios. * EntityCloner is currently built in a way that prioritizes a single entity clone * EntityCloner's recursive cloning is built to be done "inside out" in a parallel context (queue commands that each have a clone of EntityCloner). By making EntityCloner the orchestrator of the clone we can remove internal arcs, improve the clarity of the code, make EntityCloner mutable again, and simplify the builder code. * EntityCloner does not currently take into account entity mapping. This is necessary to do true "bullet proof" cloning, would allow us to unify the per-component scene spawning and cloning UX, and ultimately would allow us to use EntityCloner in place of raw reflection for scenes like `Scene(World)` (which would give us a nice performance boost: fewer archetype moves, less reflection overhead). ## Solution ### Improved Entity Mapping First, components now have first-class "entity visiting and mapping" behavior: ```rust #[derive(Component, Reflect)] #[reflect(Component)] struct Inventory { size: usize, #[entities] items: Vec<Entity>, } ``` Any field with the `#[entities]` annotation will be viewable and mappable when cloning and spawning scenes. Compare that to what was required before! ```rust #[derive(Component, Reflect, VisitEntities, VisitEntitiesMut)] #[reflect(Component, MapEntities)] struct Inventory { #[visit_entities(ignore)] size: usize, items: Vec<Entity>, } ``` Additionally, for relationships `#[entities]` is implied, meaning this "just works" in scenes and cloning: ```rust #[derive(Component, Reflect)] #[relationship(relationship_target = Children)] #[reflect(Component)] struct ChildOf(pub Entity); ``` Note that Component _does not_ implement `VisitEntities` directly. Instead, it has `Component::visit_entities` and `Component::visit_entities_mut` methods. This is for a few reasons: 1. We cannot implement `VisitEntities for C: Component` because that would conflict with our impl of VisitEntities for anything that implements `IntoIterator<Item=Entity>`. Preserving that impl is more important from a UX perspective. 2. We should not implement `Component: VisitEntities` VisitEntities in the Component derive, as that would increase the burden of manual Component trait implementors. 3. Making VisitEntitiesMut directly callable for components would make it easy to invalidate invariants defined by a component author. By putting it in the `Component` impl, we can make it harder to call naturally / unavailable to autocomplete using `fn visit_entities_mut(this: &mut Self, ...)`. `ReflectComponent::apply_or_insert` is now `ReflectComponent::apply_or_insert_mapped`. By moving mapping inside this impl, we remove the need to go through the reflection system to do entity mapping, meaning we no longer need to create a clone of the target component, map the entities in that component, and patch those values on top. This will make spawning mapped entities _much_ faster (The default `Component::visit_entities_mut` impl is an inlined empty function, so it will incur no overhead for unmapped entities). ### The Bug Fix To solve #17535, spawning code now skips entities with the new `ComponentCloneBehavior::Ignore` and `ComponentCloneBehavior::RelationshipTarget` variants (note RelationshipTarget is a temporary "workaround" variant that allows scenes to skip these components. This is a temporary workaround that can be removed as these cases should _really_ be using EntityCloner logic, which should be done in a followup PR. When that is done, `ComponentCloneBehavior::RelationshipTarget` can be merged into the normal `ComponentCloneBehavior::Custom`). ### Improved Cloning * `Option<ComponentCloneHandler>` has been replaced by `ComponentCloneBehavior`, which encodes additional intent and context (ex: `Default`, `Ignore`, `Custom`, `RelationshipTarget` (this last one is temporary)). * Global per-world entity cloning configuration has been removed. This felt overly complicated, increased our API surface, and felt too generic. Each clone context can have different requirements (ex: what a user wants in a specific system, what a scene spawner wants, etc). I'd prefer to see how far context-specific EntityCloners get us first. * EntityCloner's internals have been reworked to remove Arcs and make it mutable. * EntityCloner is now directly stored on EntityClonerBuilder, simplifying the code somewhat * EntityCloner's "bundle scratch" pattern has been moved into the new BundleScratch type, improving its usability and making it usable in other contexts (such as future cross-world cloning code). Currently this is still private, but with some higher level safe APIs it could be used externally for making dynamic bundles * EntityCloner's recursive cloning behavior has been "externalized". It is now responsible for orchestrating recursive clones, meaning it no longer needs to be sharable/clone-able across threads / read-only. * EntityCloner now does entity mapping during clones, like scenes do. This gives behavior parity and also makes it more generically useful. * `RelatonshipTarget::RECURSIVE_SPAWN` is now `RelationshipTarget::LINKED_SPAWN`, and this field is used when cloning relationship targets to determine if cloning should happen recursively. The new `LINKED_SPAWN` term was picked to make it more generically applicable across spawning and cloning scenarios. ## Next Steps * I think we should adapt EntityCloner to support cross world cloning. I think this PR helps set the stage for that by making the internals slightly more generalized. We could have a CrossWorldEntityCloner that reuses a lot of this infrastructure. * Once we support cross world cloning, we should use EntityCloner to spawn `Scene(World)` scenes. This would yield significant performance benefits (no archetype moves, less reflection overhead). --------- Co-authored-by: eugineerd <[email protected]> Co-authored-by: Alice Cecile <[email protected]>
1 parent f2a65c2 commit 3c8fae2

File tree

27 files changed

+1244
-781
lines changed

27 files changed

+1244
-781
lines changed

benches/benches/bevy_ecs/entity_cloning.rs

+28-25
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@ use core::hint::black_box;
22

33
use benches::bench;
44
use bevy_ecs::bundle::Bundle;
5-
use bevy_ecs::component::ComponentCloneHandler;
5+
use bevy_ecs::component::ComponentCloneBehavior;
6+
use bevy_ecs::entity::EntityCloner;
67
use bevy_ecs::hierarchy::ChildOf;
78
use bevy_ecs::reflect::AppTypeRegistry;
89
use bevy_ecs::{component::Component, world::World};
@@ -52,7 +53,10 @@ type ComplexBundle = (C1, C2, C3, C4, C5, C6, C7, C8, C9, C10);
5253

5354
/// Sets the [`ComponentCloneHandler`] for all explicit and required components in a bundle `B` to
5455
/// use the [`Reflect`] trait instead of [`Clone`].
55-
fn set_reflect_clone_handler<B: Bundle + GetTypeRegistration>(world: &mut World) {
56+
fn reflection_cloner<B: Bundle + GetTypeRegistration>(
57+
world: &mut World,
58+
recursive: bool,
59+
) -> EntityCloner {
5660
// Get mutable access to the type registry, creating it if it does not exist yet.
5761
let registry = world.get_resource_or_init::<AppTypeRegistry>();
5862

@@ -67,12 +71,15 @@ fn set_reflect_clone_handler<B: Bundle + GetTypeRegistration>(world: &mut World)
6771
// this bundle are saved.
6872
let component_ids: Vec<_> = world.register_bundle::<B>().contributed_components().into();
6973

70-
let clone_handlers = world.get_component_clone_handlers_mut();
74+
let mut builder = EntityCloner::build(world);
7175

7276
// Overwrite the clone handler for all components in the bundle to use `Reflect`, not `Clone`.
7377
for component in component_ids {
74-
clone_handlers.set_component_handler(component, ComponentCloneHandler::reflect_handler());
78+
builder.override_clone_behavior_with_id(component, ComponentCloneBehavior::reflect());
7579
}
80+
builder.recursive(recursive);
81+
82+
builder.finish()
7683
}
7784

7885
/// A helper function that benchmarks running the [`EntityCommands::clone_and_spawn()`] command on a
@@ -91,18 +98,18 @@ fn bench_clone<B: Bundle + Default + GetTypeRegistration>(
9198
) {
9299
let mut world = World::default();
93100

94-
if clone_via_reflect {
95-
set_reflect_clone_handler::<B>(&mut world);
96-
}
101+
let mut cloner = if clone_via_reflect {
102+
reflection_cloner::<B>(&mut world, false)
103+
} else {
104+
EntityCloner::default()
105+
};
97106

98107
// Spawn the first entity, which will be cloned in the benchmark routine.
99108
let id = world.spawn(B::default()).id();
100109

101110
b.iter(|| {
102-
// Queue the command to clone the entity.
103-
world.commands().entity(black_box(id)).clone_and_spawn();
104-
105-
// Run the command.
111+
// clones the given entity
112+
cloner.spawn_clone(&mut world, black_box(id));
106113
world.flush();
107114
});
108115
}
@@ -125,9 +132,15 @@ fn bench_clone_hierarchy<B: Bundle + Default + GetTypeRegistration>(
125132
) {
126133
let mut world = World::default();
127134

128-
if clone_via_reflect {
129-
set_reflect_clone_handler::<B>(&mut world);
130-
}
135+
let mut cloner = if clone_via_reflect {
136+
reflection_cloner::<B>(&mut world, true)
137+
} else {
138+
let mut builder = EntityCloner::build(&mut world);
139+
builder.recursive(true);
140+
builder.finish()
141+
};
142+
143+
// Make the clone command recursive, so children are cloned as well.
131144

132145
// Spawn the first entity, which will be cloned in the benchmark routine.
133146
let id = world.spawn(B::default()).id();
@@ -148,18 +161,8 @@ fn bench_clone_hierarchy<B: Bundle + Default + GetTypeRegistration>(
148161
}
149162
}
150163

151-
// Flush all `set_parent()` commands.
152-
world.flush();
153-
154164
b.iter(|| {
155-
world
156-
.commands()
157-
.entity(black_box(id))
158-
.clone_and_spawn_with(|builder| {
159-
// Make the clone command recursive, so children are cloned as well.
160-
builder.recursive(true);
161-
});
162-
165+
cloner.spawn_clone(&mut world, black_box(id));
163166
world.flush();
164167
});
165168
}

crates/bevy_animation/src/lib.rs

+4-9
Original file line numberDiff line numberDiff line change
@@ -33,12 +33,7 @@ use crate::{
3333

3434
use bevy_app::{Animation, App, Plugin, PostUpdate};
3535
use bevy_asset::{Asset, AssetApp, AssetEvents, Assets};
36-
use bevy_ecs::{
37-
entity::{VisitEntities, VisitEntitiesMut},
38-
prelude::*,
39-
reflect::{ReflectMapEntities, ReflectVisitEntities, ReflectVisitEntitiesMut},
40-
world::EntityMutExcept,
41-
};
36+
use bevy_ecs::{prelude::*, world::EntityMutExcept};
4237
use bevy_math::FloatOrd;
4338
use bevy_platform_support::{collections::HashMap, hash::NoOpHash};
4439
use bevy_reflect::{prelude::ReflectDefault, Reflect, TypePath};
@@ -207,16 +202,16 @@ impl Hash for AnimationTargetId {
207202
/// Note that each entity can only be animated by one animation player at a
208203
/// time. However, you can change [`AnimationTarget`]'s `player` property at
209204
/// runtime to change which player is responsible for animating the entity.
210-
#[derive(Clone, Copy, Component, Reflect, VisitEntities, VisitEntitiesMut)]
211-
#[reflect(Component, MapEntities, VisitEntities, VisitEntitiesMut)]
205+
#[derive(Clone, Copy, Component, Reflect)]
206+
#[reflect(Component)]
212207
pub struct AnimationTarget {
213208
/// The ID of this animation target.
214209
///
215210
/// Typically, this is derived from the path.
216-
#[visit_entities(ignore)]
217211
pub id: AnimationTargetId,
218212

219213
/// The entity containing the [`AnimationPlayer`].
214+
#[entities]
220215
pub player: Entity,
221216
}
222217

0 commit comments

Comments
 (0)