1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
use bevy::{
ecs::{
bundle::{BundleScratch, BundleWriter},
component::{ComponentId, Components, Mutable},
query::{QueryAccessError, ReleaseStateQueryData, SingleEntityQueryData},
},
prelude::*,
};
/// Like [`EntityWorldMut`], but buffers all structural changes.
///
/// Components are deserialized one by one. To avoid archetype moves or
/// triggering observers before all components have been processed, insertions
/// and removals are buffered and then applied together as a single removal
/// bundle and a single insertion bundle.
#[derive(Deref)]
pub struct DeferredEntity<'w> {
#[deref]
entity: EntityWorldMut<'w>,
buffer: EntityBuffer<'w>,
}
impl<'w> DeferredEntity<'w> {
/// Wraps an entity with scratch space to make deferred changes.
///
/// For safety / correctness, this will clear the scratch.
///
/// Note that for performance reasons this does _not_ clear the
/// allocator used for inserted components. To avoid leaking,
/// make sure insertions are followed by either
/// [`Self::flush`] or [`EntityScratch::manual_drop`].
pub fn new(entity: EntityWorldMut<'w>, scratch: &'w mut EntityScratch) -> Self {
Self {
entity,
buffer: scratch.buffer(),
}
}
/// Like [`EntityWorldMut::insert`], but accepts only a single component insertion and buffers it.
///
/// Calling this function multiple times for different components is equivalent to inserting a bundle with them.
pub fn insert<C: Component>(&mut self, component: C) -> &mut Self {
// SAFETY: no location update is needed because we only access the registrator
// from the world, and it is from the same world as the entity.
unsafe {
let mut registrator = self.entity.world_mut().components_registrator();
self.buffer
.insertions
.push_component(&mut registrator, component);
}
self
}
/// Like [`EntityWorldMut::remove`], but accepts only a single component removal and buffers it.
///
/// Calling this function multiple times for different components is equivalent to removing a bundle with them.
pub fn remove<C: Component>(&mut self) -> &mut Self {
let component_id = self.register_component::<C>();
self.buffer.removals.push(component_id);
self
}
/// Like [`EntityWorldMut::remove_with_requires`], but accepts only a single component and buffers it.
///
/// Calling this function multiple times for different components is equivalent to removing a bundle with them.
pub fn remove_with_requires<C: Component>(&mut self) -> &mut Self {
let component_id = self.register_component::<C>();
self.buffer.removals.push(component_id);
let components = self.entity.world().components();
// SAFETY: the ID was registered above.
let info = unsafe { components.get_info_unchecked(component_id) };
for required_id in info.required_components().iter_ids() {
self.buffer.removals.push(required_id);
}
self
}
/// Gets mutable access to the component of type `C` for the current entity.
///
/// Returns `None` if the entity does not have a component of type `C`.
#[inline]
pub fn get_mut<C: Component<Mutability = Mutable>>(&mut self) -> Option<Mut<'_, C>> {
self.entity.get_mut()
}
/// Returns components for the current entity that match the query `Q`.
///
/// For more details, see [`EntityWorldMut::get_components_mut`].
#[inline]
pub fn get_components_mut<Q: ReleaseStateQueryData + SingleEntityQueryData>(
&mut self,
) -> Result<Q::Item<'_, 'static>, QueryAccessError> {
self.entity.get_components_mut::<Q>()
}
/// Like [`Self::get_components_mut_unchecked`], but doesn't check for aliasing.
///
/// For more details, see [`EntityWorldMut::get_components_mut`].
///
/// # Safety
///
/// The caller must ensure that `Q` does not provide aliasing mutable references to the same component.
#[inline]
pub unsafe fn get_components_mut_unchecked<Q: ReleaseStateQueryData + SingleEntityQueryData>(
&mut self,
) -> Result<Q::Item<'_, 'static>, QueryAccessError> {
unsafe { self.entity.get_components_mut_unchecked::<Q>() }
}
fn register_component<C: Component>(&mut self) -> ComponentId {
// SAFETY: no location update is needed because we only register the component ID.
unsafe { self.world_mut().register_component::<C>() }
}
/// Returns this entity's world.
///
/// # Safety
///
/// All safety requirements of [`EntityWorldMut::world_mut`] apply. In addition,
/// [`EntityAllocator`](bevy::ecs::entity::EntityAllocator) must not be mutably
/// borrowed, which means that no entities can be freed
/// (spawning new entities is safe).
pub unsafe fn world_mut(&mut self) -> &mut World {
unsafe { self.entity.world_mut() }
}
/// Flushes buffered changes to the entity and clears the scratch.
pub fn flush(mut self) {
// SAFETY: All buffered components were recorded using the same world
// that entity belongs to.
unsafe { self.buffer.write(&mut self.entity) };
}
}
#[deprecated(note = "renamed into `EntityScratch`")]
pub type DeferredChanges = EntityScratch;
/// Like [`BundleScratch`], but can also buffer removals.
#[derive(Default)]
pub struct EntityScratch {
insertions: BundleScratch,
removals: Vec<ComponentId>,
}
impl EntityScratch {
fn buffer<'a>(&'a mut self) -> EntityBuffer<'a> {
debug_assert!(
self.insertions.is_empty(),
"insertions should be cleared to avoid leaking"
);
self.removals.clear();
EntityBuffer {
removals: &mut self.removals,
insertions: self.insertions.writer(),
}
}
/// Drops all components currently stored in the scratch space.
///
/// # Safety
///
/// `components` must come from the same world as the components that
/// were pushed into this buffer.
pub unsafe fn manual_drop(&mut self, components: &Components) {
unsafe { self.insertions.manual_drop(components) };
}
}
/// Borrowed buffer used by [`DeferredEntity`] to stage structural changes.
struct EntityBuffer<'a> {
insertions: BundleWriter<'a>,
removals: &'a mut Vec<ComponentId>,
}
impl EntityBuffer<'_> {
/// Writes all buffered changes to the entity.
///
/// # Safety
///
/// All insertions must have been pushed using the same world
/// as the entity.
unsafe fn write(self, entity: &mut EntityWorldMut) {
if !self.removals.is_empty() {
entity.remove_by_ids(self.removals);
self.removals.clear();
}
if !self.insertions.is_empty() {
unsafe { self.insertions.write(entity) };
}
}
}
#[cfg(test)]
mod tests {
use alloc::sync::Arc;
use core::any::Any;
use super::*;
#[test]
fn buffering() {
let mut world = World::new();
let before_archetypes = world.archetypes().len();
let mut scratch = EntityScratch::default();
let mut entity = DeferredEntity::new(world.spawn_empty(), &mut scratch);
let entity_id = entity.id();
entity
.insert(Unit)
.insert(WithRequired)
.insert(Trivial(1))
.insert(WithVec(vec![2, 3]))
.insert(WithBox(Box::new(Trivial(4))))
.insert(WithArc(Arc::new(Trivial(5))));
entity.flush();
let mut entity = DeferredEntity::new(world.entity_mut(entity_id), &mut scratch);
assert!(entity.get::<Unit>().is_some());
assert!(entity.get::<WithRequired>().is_some());
assert!(entity.get::<Required>().is_some());
assert_eq!(**entity.get::<Trivial>().unwrap(), 1);
assert_eq!(**entity.get::<WithVec>().unwrap(), [2, 3]);
let with_box = entity.get::<WithBox>().unwrap();
assert_eq!(**with_box.downcast_ref::<Trivial>().unwrap(), 4);
let with_arc = entity.get::<WithArc>().unwrap();
assert_eq!(Arc::strong_count(with_arc), 1);
assert_eq!(**with_arc.downcast_ref::<Trivial>().unwrap(), 5);
let after_archetypes = entity.world().archetypes().len();
assert_eq!(
after_archetypes - before_archetypes,
1,
"insertions should batch into one archetype move"
);
entity
.remove::<Unit>()
.remove_with_requires::<WithRequired>()
.remove::<Trivial>()
.remove::<WithVec>()
.remove::<WithBox>()
.remove::<WithArc>();
entity.flush();
let entity = world.entity(entity_id);
assert!(!entity.contains::<Unit>());
assert!(!entity.contains::<WithRequired>());
assert!(!entity.contains::<Required>());
assert!(!entity.contains::<Trivial>());
assert!(!entity.contains::<WithVec>());
assert!(!entity.contains::<WithBox>());
assert!(!entity.contains::<WithArc>());
assert_eq!(
world.archetypes().len(),
after_archetypes,
"removals shouldn't create intermediate archetypes"
);
}
#[derive(Component)]
struct Unit;
#[derive(Component)]
#[require(Required)]
struct WithRequired;
#[derive(Component, Default)]
struct Required;
#[derive(Component, Deref)]
struct Trivial(usize);
#[derive(Component, Deref)]
struct WithVec(Vec<u8>);
#[derive(Component, Deref)]
struct WithBox(Box<dyn Any + Send + Sync>);
#[derive(Component, Deref)]
struct WithArc(Arc<dyn Any + Send + Sync>);
}