bevy_ecs/reflect/component.rs
1//! Definitions for [`Component`] reflection.
2//! This allows inserting, updating, removing and generally interacting with components
3//! whose types are only known at runtime.
4//!
5//! This module exports two types: [`ReflectComponentFns`] and [`ReflectComponent`].
6//!
7//! # Architecture
8//!
9//! [`ReflectComponent`] wraps a [`ReflectComponentFns`]. In fact, each method on
10//! [`ReflectComponent`] wraps a call to a function pointer field in `ReflectComponentFns`.
11//!
12//! ## Who creates `ReflectComponent`s?
13//!
14//! When a user adds the `#[reflect(Component)]` attribute to their `#[derive(Reflect)]`
15//! type, it tells the derive macro for `Reflect` to add the following single line to its
16//! [`get_type_registration`] method (see the relevant code[^1]).
17//!
18//! ```
19//! # use bevy_reflect::{FromType, Reflect};
20//! # use bevy_ecs::prelude::{ReflectComponent, Component};
21//! # #[derive(Default, Reflect, Component)]
22//! # struct A;
23//! # impl A {
24//! # fn foo() {
25//! # let mut registration = bevy_reflect::TypeRegistration::of::<A>();
26//! registration.insert::<ReflectComponent>(FromType::<Self>::from_type());
27//! # }
28//! # }
29//! ```
30//!
31//! This line adds a `ReflectComponent` to the registration data for the type in question.
32//! The user can access the `ReflectComponent` for type `T` through the type registry,
33//! as per the `trait_reflection.rs` example.
34//!
35//! The `FromType::<Self>::from_type()` in the previous line calls the `FromType<C>`
36//! implementation of `ReflectComponent`.
37//!
38//! The `FromType<C>` impl creates a function per field of [`ReflectComponentFns`].
39//! In those functions, we call generic methods on [`World`] and [`EntityWorldMut`].
40//!
41//! The result is a `ReflectComponent` completely independent of `C`, yet capable
42//! of using generic ECS methods such as `entity.get::<C>()` to get `&dyn Reflect`
43//! with underlying type `C`, without the `C` appearing in the type signature.
44//!
45//! ## A note on code generation
46//!
47//! A downside of this approach is that monomorphized code (ie: concrete code
48//! for generics) is generated **unconditionally**, regardless of whether it ends
49//! up used or not.
50//!
51//! Adding `N` fields on `ReflectComponentFns` will generate `N × M` additional
52//! functions, where `M` is how many types derive `#[reflect(Component)]`.
53//!
54//! Those functions will increase the size of the final app binary.
55//!
56//! [^1]: `crates/bevy_reflect/bevy_reflect_derive/src/registration.rs`
57//!
58//! [`get_type_registration`]: bevy_reflect::GetTypeRegistration::get_type_registration
59
60use super::from_reflect_with_fallback;
61use crate::{
62 change_detection::Mut,
63 component::{ComponentId, ComponentMutability},
64 entity::{Entity, EntityMapper},
65 prelude::Component,
66 relationship::RelationshipHookMode,
67 world::{
68 unsafe_world_cell::UnsafeEntityCell, EntityMut, EntityWorldMut, FilteredEntityMut,
69 FilteredEntityRef, World,
70 },
71};
72use bevy_reflect::{FromReflect, FromType, PartialReflect, Reflect, TypePath, TypeRegistry};
73use disqualified::ShortName;
74
75/// A struct used to operate on reflected [`Component`] trait of a type.
76///
77/// A [`ReflectComponent`] for type `T` can be obtained via
78/// [`bevy_reflect::TypeRegistration::data`].
79#[derive(Clone)]
80pub struct ReflectComponent(ReflectComponentFns);
81
82/// The raw function pointers needed to make up a [`ReflectComponent`].
83///
84/// This is used when creating custom implementations of [`ReflectComponent`] with
85/// [`ReflectComponent::new()`].
86///
87/// > **Note:**
88/// > Creating custom implementations of [`ReflectComponent`] is an advanced feature that most users
89/// > will not need.
90/// > Usually a [`ReflectComponent`] is created for a type by deriving [`Reflect`]
91/// > and adding the `#[reflect(Component)]` attribute.
92/// > After adding the component to the [`TypeRegistry`],
93/// > its [`ReflectComponent`] can then be retrieved when needed.
94///
95/// Creating a custom [`ReflectComponent`] may be useful if you need to create new component types
96/// at runtime, for example, for scripting implementations.
97///
98/// By creating a custom [`ReflectComponent`] and inserting it into a type's
99/// [`TypeRegistration`][bevy_reflect::TypeRegistration],
100/// you can modify the way that reflected components of that type will be inserted into the Bevy
101/// world.
102#[derive(Clone)]
103pub struct ReflectComponentFns {
104 /// Function pointer implementing [`ReflectComponent::insert()`].
105 pub insert: fn(&mut EntityWorldMut, &dyn PartialReflect, &TypeRegistry),
106 /// Function pointer implementing [`ReflectComponent::apply()`].
107 pub apply: fn(EntityMut, &dyn PartialReflect),
108 /// Function pointer implementing [`ReflectComponent::apply_or_insert_mapped()`].
109 pub apply_or_insert_mapped: fn(
110 &mut EntityWorldMut,
111 &dyn PartialReflect,
112 &TypeRegistry,
113 &mut dyn EntityMapper,
114 RelationshipHookMode,
115 ),
116 /// Function pointer implementing [`ReflectComponent::remove()`].
117 pub remove: fn(&mut EntityWorldMut),
118 /// Function pointer implementing [`ReflectComponent::contains()`].
119 pub contains: fn(FilteredEntityRef) -> bool,
120 /// Function pointer implementing [`ReflectComponent::reflect()`].
121 pub reflect: fn(FilteredEntityRef) -> Option<&dyn Reflect>,
122 /// Function pointer implementing [`ReflectComponent::reflect_mut()`].
123 pub reflect_mut: fn(FilteredEntityMut) -> Option<Mut<dyn Reflect>>,
124 /// Function pointer implementing [`ReflectComponent::map_entities()`].
125 pub map_entities: fn(&mut dyn Reflect, &mut dyn EntityMapper),
126 /// Function pointer implementing [`ReflectComponent::reflect_unchecked_mut()`].
127 ///
128 /// # Safety
129 /// The function may only be called with an [`UnsafeEntityCell`] that can be used to mutably access the relevant component on the given entity.
130 pub reflect_unchecked_mut: unsafe fn(UnsafeEntityCell<'_>) -> Option<Mut<'_, dyn Reflect>>,
131 /// Function pointer implementing [`ReflectComponent::copy()`].
132 pub copy: fn(&World, &mut World, Entity, Entity, &TypeRegistry),
133 /// Function pointer implementing [`ReflectComponent::register_component()`].
134 pub register_component: fn(&mut World) -> ComponentId,
135}
136
137impl ReflectComponentFns {
138 /// Get the default set of [`ReflectComponentFns`] for a specific component type using its
139 /// [`FromType`] implementation.
140 ///
141 /// This is useful if you want to start with the default implementation before overriding some
142 /// of the functions to create a custom implementation.
143 pub fn new<T: Component + FromReflect + TypePath>() -> Self {
144 <ReflectComponent as FromType<T>>::from_type().0
145 }
146}
147
148impl ReflectComponent {
149 /// Insert a reflected [`Component`] into the entity like [`insert()`](EntityWorldMut::insert).
150 pub fn insert(
151 &self,
152 entity: &mut EntityWorldMut,
153 component: &dyn PartialReflect,
154 registry: &TypeRegistry,
155 ) {
156 (self.0.insert)(entity, component, registry);
157 }
158
159 /// Uses reflection to set the value of this [`Component`] type in the entity to the given value.
160 ///
161 /// # Panics
162 ///
163 /// Panics if there is no [`Component`] of the given type.
164 ///
165 /// Will also panic if [`Component`] is immutable.
166 pub fn apply<'a>(&self, entity: impl Into<EntityMut<'a>>, component: &dyn PartialReflect) {
167 (self.0.apply)(entity.into(), component);
168 }
169
170 /// Uses reflection to set the value of this [`Component`] type in the entity to the given value or insert a new one if it does not exist.
171 ///
172 /// # Panics
173 ///
174 /// Panics if [`Component`] is immutable.
175 pub fn apply_or_insert_mapped(
176 &self,
177 entity: &mut EntityWorldMut,
178 component: &dyn PartialReflect,
179 registry: &TypeRegistry,
180 map: &mut dyn EntityMapper,
181 relationship_hook_mode: RelationshipHookMode,
182 ) {
183 (self.0.apply_or_insert_mapped)(entity, component, registry, map, relationship_hook_mode);
184 }
185
186 /// Removes this [`Component`] type from the entity. Does nothing if it doesn't exist.
187 pub fn remove(&self, entity: &mut EntityWorldMut) {
188 (self.0.remove)(entity);
189 }
190
191 /// Returns whether entity contains this [`Component`]
192 pub fn contains<'a>(&self, entity: impl Into<FilteredEntityRef<'a>>) -> bool {
193 (self.0.contains)(entity.into())
194 }
195
196 /// Gets the value of this [`Component`] type from the entity as a reflected reference.
197 pub fn reflect<'a>(&self, entity: impl Into<FilteredEntityRef<'a>>) -> Option<&'a dyn Reflect> {
198 (self.0.reflect)(entity.into())
199 }
200
201 /// Gets the value of this [`Component`] type from the entity as a mutable reflected reference.
202 ///
203 /// # Panics
204 ///
205 /// Panics if [`Component`] is immutable.
206 pub fn reflect_mut<'a>(
207 &self,
208 entity: impl Into<FilteredEntityMut<'a>>,
209 ) -> Option<Mut<'a, dyn Reflect>> {
210 (self.0.reflect_mut)(entity.into())
211 }
212
213 /// # Safety
214 /// This method does not prevent you from having two mutable pointers to the same data,
215 /// violating Rust's aliasing rules. To avoid this:
216 /// * Only call this method with a [`UnsafeEntityCell`] that may be used to mutably access the component on the entity `entity`
217 /// * Don't call this method more than once in the same scope for a given [`Component`].
218 ///
219 /// # Panics
220 ///
221 /// Panics if [`Component`] is immutable.
222 pub unsafe fn reflect_unchecked_mut<'a>(
223 &self,
224 entity: UnsafeEntityCell<'a>,
225 ) -> Option<Mut<'a, dyn Reflect>> {
226 // SAFETY: safety requirements deferred to caller
227 unsafe { (self.0.reflect_unchecked_mut)(entity) }
228 }
229
230 /// Gets the value of this [`Component`] type from entity from `source_world` and [applies](Self::apply()) it to the value of this [`Component`] type in entity in `destination_world`.
231 ///
232 /// # Panics
233 ///
234 /// Panics if there is no [`Component`] of the given type or either entity does not exist.
235 pub fn copy(
236 &self,
237 source_world: &World,
238 destination_world: &mut World,
239 source_entity: Entity,
240 destination_entity: Entity,
241 registry: &TypeRegistry,
242 ) {
243 (self.0.copy)(
244 source_world,
245 destination_world,
246 source_entity,
247 destination_entity,
248 registry,
249 );
250 }
251
252 /// Register the type of this [`Component`] in [`World`], returning its [`ComponentId`].
253 pub fn register_component(&self, world: &mut World) -> ComponentId {
254 (self.0.register_component)(world)
255 }
256
257 /// Create a custom implementation of [`ReflectComponent`].
258 ///
259 /// This is an advanced feature,
260 /// useful for scripting implementations,
261 /// that should not be used by most users
262 /// unless you know what you are doing.
263 ///
264 /// Usually you should derive [`Reflect`] and add the `#[reflect(Component)]` component
265 /// to generate a [`ReflectComponent`] implementation automatically.
266 ///
267 /// See [`ReflectComponentFns`] for more information.
268 pub fn new(fns: ReflectComponentFns) -> Self {
269 Self(fns)
270 }
271
272 /// The underlying function pointers implementing methods on `ReflectComponent`.
273 ///
274 /// This is useful when you want to keep track locally of an individual
275 /// function pointer.
276 ///
277 /// Calling [`TypeRegistry::get`] followed by
278 /// [`TypeRegistration::data::<ReflectComponent>`] can be costly if done several
279 /// times per frame. Consider cloning [`ReflectComponent`] and keeping it
280 /// between frames, cloning a `ReflectComponent` is very cheap.
281 ///
282 /// If you only need a subset of the methods on `ReflectComponent`,
283 /// use `fn_pointers` to get the underlying [`ReflectComponentFns`]
284 /// and copy the subset of function pointers you care about.
285 ///
286 /// [`TypeRegistration::data::<ReflectComponent>`]: bevy_reflect::TypeRegistration::data
287 /// [`TypeRegistry::get`]: bevy_reflect::TypeRegistry::get
288 pub fn fn_pointers(&self) -> &ReflectComponentFns {
289 &self.0
290 }
291
292 /// Calls a dynamic version of [`Component::map_entities`].
293 pub fn map_entities(&self, component: &mut dyn Reflect, func: &mut dyn EntityMapper) {
294 (self.0.map_entities)(component, func);
295 }
296}
297
298impl<C: Component + Reflect + TypePath> FromType<C> for ReflectComponent {
299 fn from_type() -> Self {
300 // TODO: Currently we panic if a component is immutable and you use
301 // reflection to mutate it. Perhaps the mutation methods should be fallible?
302 ReflectComponent(ReflectComponentFns {
303 insert: |entity, reflected_component, registry| {
304 let component = entity.world_scope(|world| {
305 from_reflect_with_fallback::<C>(reflected_component, world, registry)
306 });
307 entity.insert(component);
308 },
309 apply: |mut entity, reflected_component| {
310 if !C::Mutability::MUTABLE {
311 let name = ShortName::of::<C>();
312 panic!("Cannot call `ReflectComponent::apply` on component {name}. It is immutable, and cannot modified through reflection");
313 }
314
315 // SAFETY: guard ensures `C` is a mutable component
316 let mut component = unsafe { entity.get_mut_assume_mutable::<C>() }.unwrap();
317 component.apply(reflected_component);
318 },
319 apply_or_insert_mapped: |entity,
320 reflected_component,
321 registry,
322 mut mapper,
323 relationship_hook_mode| {
324 if C::Mutability::MUTABLE {
325 // SAFETY: guard ensures `C` is a mutable component
326 if let Some(mut component) = unsafe { entity.get_mut_assume_mutable::<C>() } {
327 component.apply(reflected_component.as_partial_reflect());
328 C::map_entities(&mut component, &mut mapper);
329 } else {
330 let mut component = entity.world_scope(|world| {
331 from_reflect_with_fallback::<C>(reflected_component, world, registry)
332 });
333 C::map_entities(&mut component, &mut mapper);
334 entity
335 .insert_with_relationship_hook_mode(component, relationship_hook_mode);
336 }
337 } else {
338 let mut component = entity.world_scope(|world| {
339 from_reflect_with_fallback::<C>(reflected_component, world, registry)
340 });
341 C::map_entities(&mut component, &mut mapper);
342 entity.insert_with_relationship_hook_mode(component, relationship_hook_mode);
343 }
344 },
345 remove: |entity| {
346 entity.remove::<C>();
347 },
348 contains: |entity| entity.contains::<C>(),
349 copy: |source_world, destination_world, source_entity, destination_entity, registry| {
350 let source_component = source_world.get::<C>(source_entity).unwrap();
351 let destination_component =
352 from_reflect_with_fallback::<C>(source_component, destination_world, registry);
353 destination_world
354 .entity_mut(destination_entity)
355 .insert(destination_component);
356 },
357 reflect: |entity| entity.get::<C>().map(|c| c as &dyn Reflect),
358 reflect_mut: |entity| {
359 if !C::Mutability::MUTABLE {
360 let name = ShortName::of::<C>();
361 panic!("Cannot call `ReflectComponent::reflect_mut` on component {name}. It is immutable, and cannot modified through reflection");
362 }
363
364 // SAFETY: guard ensures `C` is a mutable component
365 unsafe {
366 entity
367 .into_mut_assume_mutable::<C>()
368 .map(|c| c.map_unchanged(|value| value as &mut dyn Reflect))
369 }
370 },
371 reflect_unchecked_mut: |entity| {
372 if !C::Mutability::MUTABLE {
373 let name = ShortName::of::<C>();
374 panic!("Cannot call `ReflectComponent::reflect_unchecked_mut` on component {name}. It is immutable, and cannot modified through reflection");
375 }
376
377 // SAFETY: reflect_unchecked_mut is an unsafe function pointer used by
378 // `reflect_unchecked_mut` which must be called with an UnsafeEntityCell with access to the component `C` on the `entity`
379 // guard ensures `C` is a mutable component
380 let c = unsafe { entity.get_mut_assume_mutable::<C>() };
381 c.map(|c| c.map_unchanged(|value| value as &mut dyn Reflect))
382 },
383 register_component: |world: &mut World| -> ComponentId {
384 world.register_component::<C>()
385 },
386 map_entities: |reflect: &mut dyn Reflect, mut mapper: &mut dyn EntityMapper| {
387 let component = reflect.downcast_mut::<C>().unwrap();
388 Component::map_entities(component, &mut mapper);
389 },
390 })
391 }
392}