Skip to content

Commit af19fc5

Browse files
Shaturjames7132
authored andcommitted
Add reflection for resources (bevyengine#5175)
# Objective We don't have reflection for resources. ## Solution Introduce reflection for resources. Continues bevyengine#3580 (by @Davier), related to bevyengine#3576. --- ## Changelog ### Added * Reflection on a resource type (by adding `ReflectResource`): ```rust #[derive(Reflect)] #[reflect(Resource)] struct MyResourse; ``` ### Changed * Rename `ReflectComponent::add_component` into `ReflectComponent::insert_component` for consistency. ## Migration Guide * Rename `ReflectComponent::add_component` into `ReflectComponent::insert_component`.
1 parent 47496f3 commit af19fc5

File tree

9 files changed

+154
-12
lines changed

9 files changed

+154
-12
lines changed

crates/bevy_core_pipeline/src/clear_color.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,8 @@ pub enum ClearColorConfig {
1717
///
1818
/// This color appears as the "background" color for simple apps, when
1919
/// there are portions of the screen with nothing rendered.
20-
#[derive(Component, Clone, Debug, Deref, DerefMut, ExtractResource)]
20+
#[derive(Component, Clone, Debug, Deref, DerefMut, ExtractResource, Reflect)]
21+
#[reflect(Resource)]
2122
pub struct ClearColor(pub Color);
2223

2324
impl Default for ClearColor {

crates/bevy_core_pipeline/src/lib.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,8 @@ pub struct CorePipelinePlugin;
2020

2121
impl Plugin for CorePipelinePlugin {
2222
fn build(&self, app: &mut App) {
23-
app.init_resource::<ClearColor>()
23+
app.register_type::<ClearColor>()
24+
.init_resource::<ClearColor>()
2425
.add_plugin(ExtractResourcePlugin::<ClearColor>::default())
2526
.add_plugin(Core2dPlugin)
2627
.add_plugin(Core3dPlugin);

crates/bevy_ecs/src/change_detection.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -216,7 +216,7 @@ change_detection_impl!(Mut<'a, T>, T,);
216216
impl_into_inner!(Mut<'a, T>, T,);
217217
impl_debug!(Mut<'a, T>,);
218218

219-
/// Unique mutable borrow of a Reflected component
219+
/// Unique mutable borrow of a reflected component or resource
220220
#[cfg(feature = "bevy_reflect")]
221221
pub struct ReflectMut<'a> {
222222
pub(crate) value: &'a mut dyn Reflect,

crates/bevy_ecs/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ pub use bevy_ptr as ptr;
2323
pub mod prelude {
2424
#[doc(hidden)]
2525
#[cfg(feature = "bevy_reflect")]
26-
pub use crate::reflect::ReflectComponent;
26+
pub use crate::reflect::{ReflectComponent, ReflectResource};
2727
#[doc(hidden)]
2828
pub use crate::{
2929
bundle::Bundle,

crates/bevy_ecs/src/reflect.rs

Lines changed: 130 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,18 @@ pub use crate::change_detection::ReflectMut;
44
use crate::{
55
component::Component,
66
entity::{Entity, EntityMap, MapEntities, MapEntitiesError},
7+
system::Resource,
78
world::{FromWorld, World},
89
};
910
use bevy_reflect::{
1011
impl_from_reflect_value, impl_reflect_value, FromType, Reflect, ReflectDeserialize,
1112
ReflectSerialize,
1213
};
1314

15+
/// A struct used to operate on reflected [`Component`] of a type.
16+
///
17+
/// A [`ReflectComponent`] for type `T` can be obtained via
18+
/// [`bevy_reflect::TypeRegistration::data`].
1419
#[derive(Clone)]
1520
pub struct ReflectComponent {
1621
add_component: fn(&mut World, Entity, &dyn Reflect),
@@ -22,18 +27,34 @@ pub struct ReflectComponent {
2227
}
2328

2429
impl ReflectComponent {
30+
/// Insert a reflected [`Component`] into the entity like [`insert()`](crate::world::EntityMut::insert).
31+
///
32+
/// # Panics
33+
///
34+
/// Panics if there is no such entity.
2535
pub fn add_component(&self, world: &mut World, entity: Entity, component: &dyn Reflect) {
2636
(self.add_component)(world, entity, component);
2737
}
2838

39+
/// Uses reflection to set the value of this [`Component`] type in the entity to the given value.
40+
///
41+
/// # Panics
42+
///
43+
/// Panics if there is no [`Component`] of the given type or the `entity` does not exist.
2944
pub fn apply_component(&self, world: &mut World, entity: Entity, component: &dyn Reflect) {
3045
(self.apply_component)(world, entity, component);
3146
}
3247

48+
/// Removes this [`Component`] type from the entity. Does nothing if it doesn't exist.
49+
///
50+
/// # Panics
51+
///
52+
/// Panics if there is no [`Component`] of the given type or the `entity` does not exist.
3353
pub fn remove_component(&self, world: &mut World, entity: Entity) {
3454
(self.remove_component)(world, entity);
3555
}
3656

57+
/// Gets the value of this [`Component`] type from the entity as a reflected reference.
3758
pub fn reflect_component<'a>(
3859
&self,
3960
world: &'a World,
@@ -42,6 +63,7 @@ impl ReflectComponent {
4263
(self.reflect_component)(world, entity)
4364
}
4465

66+
/// Gets the value of this [`Component`] type from the entity as a mutable reflected reference.
4567
pub fn reflect_component_mut<'a>(
4668
&self,
4769
world: &'a mut World,
@@ -56,7 +78,7 @@ impl ReflectComponent {
5678
/// violating Rust's aliasing rules. To avoid this:
5779
/// * Only call this method in an exclusive system to avoid sharing across threads (or use a
5880
/// scheduler that enforces safe memory access).
59-
/// * Don't call this method more than once in the same scope for a given component.
81+
/// * Don't call this method more than once in the same scope for a given [`Component`].
6082
pub unsafe fn reflect_component_unchecked_mut<'a>(
6183
&self,
6284
world: &'a World,
@@ -65,6 +87,11 @@ impl ReflectComponent {
6587
(self.reflect_component_mut)(world, entity)
6688
}
6789

90+
/// Gets the value of this [`Component`] type from entity from `source_world` and [applies](Self::apply_component()) it to the value of this [`Component`] type in entity in `destination_world`.
91+
///
92+
/// # Panics
93+
///
94+
/// Panics if there is no [`Component`] of the given type or either entity does not exist.
6895
pub fn copy_component(
6996
&self,
7097
source_world: &World,
@@ -123,6 +150,108 @@ impl<C: Component + Reflect + FromWorld> FromType<C> for ReflectComponent {
123150
}
124151
}
125152

153+
/// A struct used to operate on reflected [`Resource`] of a type.
154+
///
155+
/// A [`ReflectResource`] for type `T` can be obtained via
156+
/// [`bevy_reflect::TypeRegistration::data`].
157+
#[derive(Clone)]
158+
pub struct ReflectResource {
159+
insert_resource: fn(&mut World, &dyn Reflect),
160+
apply_resource: fn(&mut World, &dyn Reflect),
161+
remove_resource: fn(&mut World),
162+
reflect_resource: fn(&World) -> Option<&dyn Reflect>,
163+
reflect_resource_unchecked_mut: unsafe fn(&World) -> Option<ReflectMut>,
164+
copy_resource: fn(&World, &mut World),
165+
}
166+
167+
impl ReflectResource {
168+
/// Insert a reflected [`Resource`] into the world like [`insert_resource()`](World::insert_resource).
169+
pub fn insert_resource(&self, world: &mut World, resource: &dyn Reflect) {
170+
(self.insert_resource)(world, resource);
171+
}
172+
173+
/// Uses reflection to set the value of this [`Resource`] type in the world to the given value.
174+
///
175+
/// # Panics
176+
///
177+
/// Panics if there is no [`Resource`] of the given type.
178+
pub fn apply_resource(&self, world: &mut World, resource: &dyn Reflect) {
179+
(self.apply_resource)(world, resource);
180+
}
181+
182+
/// Removes this [`Resource`] type from the world. Does nothing if it doesn't exist.
183+
pub fn remove_resource(&self, world: &mut World) {
184+
(self.remove_resource)(world);
185+
}
186+
187+
/// Gets the value of this [`Resource`] type from the world as a reflected reference.
188+
pub fn reflect_resource<'a>(&self, world: &'a World) -> Option<&'a dyn Reflect> {
189+
(self.reflect_resource)(world)
190+
}
191+
192+
/// Gets the value of this [`Resource`] type from the world as a mutable reflected reference.
193+
pub fn reflect_resource_mut<'a>(&self, world: &'a mut World) -> Option<ReflectMut<'a>> {
194+
// SAFE: unique world access
195+
unsafe { (self.reflect_resource_unchecked_mut)(world) }
196+
}
197+
198+
/// # Safety
199+
/// This method does not prevent you from having two mutable pointers to the same data,
200+
/// violating Rust's aliasing rules. To avoid this:
201+
/// * Only call this method in an exclusive system to avoid sharing across threads (or use a
202+
/// scheduler that enforces safe memory access).
203+
/// * Don't call this method more than once in the same scope for a given [`Resource`].
204+
pub unsafe fn reflect_resource_unckecked_mut<'a>(
205+
&self,
206+
world: &'a World,
207+
) -> Option<ReflectMut<'a>> {
208+
(self.reflect_resource_unchecked_mut)(world)
209+
}
210+
211+
/// Gets the value of this [`Resource`] type from `source_world` and [applies](Self::apply_resource()) it to the value of this [`Resource`] type in `destination_world`.
212+
///
213+
/// # Panics
214+
///
215+
/// Panics if there is no [`Resource`] of the given type.
216+
pub fn copy_resource(&self, source_world: &World, destination_world: &mut World) {
217+
(self.copy_resource)(source_world, destination_world);
218+
}
219+
}
220+
221+
impl<C: Resource + Reflect + FromWorld> FromType<C> for ReflectResource {
222+
fn from_type() -> Self {
223+
ReflectResource {
224+
insert_resource: |world, reflected_resource| {
225+
let mut resource = C::from_world(world);
226+
resource.apply(reflected_resource);
227+
world.insert_resource(resource);
228+
},
229+
apply_resource: |world, reflected_resource| {
230+
let mut resource = world.resource_mut::<C>();
231+
resource.apply(reflected_resource);
232+
},
233+
remove_resource: |world| {
234+
world.remove_resource::<C>();
235+
},
236+
reflect_resource: |world| world.get_resource::<C>().map(|res| res as &dyn Reflect),
237+
reflect_resource_unchecked_mut: |world| unsafe {
238+
world
239+
.get_resource_unchecked_mut::<C>()
240+
.map(|res| ReflectMut {
241+
value: res.value as &mut dyn Reflect,
242+
ticks: res.ticks,
243+
})
244+
},
245+
copy_resource: |source_world, destination_world| {
246+
let source_resource = source_world.resource::<C>();
247+
let mut destination_resource = C::from_world(destination_world);
248+
destination_resource.apply(source_resource);
249+
destination_world.insert_resource(destination_resource);
250+
},
251+
}
252+
}
253+
}
254+
126255
impl_reflect_value!(Entity(Hash, PartialEq, Serialize, Deserialize));
127256
impl_from_reflect_value!(Entity);
128257

crates/bevy_pbr/src/lib.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,9 @@ impl Plugin for PbrPlugin {
125125
.register_type::<PointLight>()
126126
.add_plugin(MeshRenderPlugin)
127127
.add_plugin(MaterialPlugin::<StandardMaterial>::default())
128+
.register_type::<AmbientLight>()
129+
.register_type::<DirectionalLightShadowMap>()
130+
.register_type::<PointLightShadowMap>()
128131
.init_resource::<AmbientLight>()
129132
.init_resource::<GlobalVisiblePointLights>()
130133
.init_resource::<DirectionalLightShadowMap>()

crates/bevy_pbr/src/light.rs

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,8 @@ impl PointLight {
7373
pub const DEFAULT_SHADOW_NORMAL_BIAS: f32 = 0.6;
7474
}
7575

76-
#[derive(Clone, Debug)]
76+
#[derive(Clone, Debug, Reflect)]
77+
#[reflect(Resource)]
7778
pub struct PointLightShadowMap {
7879
pub size: usize,
7980
}
@@ -151,7 +152,8 @@ impl DirectionalLight {
151152
pub const DEFAULT_SHADOW_NORMAL_BIAS: f32 = 0.6;
152153
}
153154

154-
#[derive(Clone, Debug)]
155+
#[derive(Clone, Debug, Reflect)]
156+
#[reflect(Resource)]
155157
pub struct DirectionalLightShadowMap {
156158
pub size: usize,
157159
}
@@ -166,7 +168,8 @@ impl Default for DirectionalLightShadowMap {
166168
}
167169

168170
/// An ambient light, which lights the entire scene equally.
169-
#[derive(Clone, Debug, ExtractResource)]
171+
#[derive(Clone, Debug, ExtractResource, Reflect)]
172+
#[reflect(Resource)]
170173
pub struct AmbientLight {
171174
pub color: Color,
172175
/// A direct scale factor multiplied with `color` before being passed to the shader.

crates/bevy_pbr/src/wireframe.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,8 @@ impl Plugin for WireframePlugin {
3535
Shader::from_wgsl
3636
);
3737

38-
app.init_resource::<WireframeConfig>()
38+
app.register_type::<WireframeConfig>()
39+
.init_resource::<WireframeConfig>()
3940
.add_plugin(ExtractResourcePlugin::<WireframeConfig>::default());
4041

4142
if let Ok(render_app) = app.get_sub_app_mut(RenderApp) {
@@ -60,7 +61,8 @@ fn extract_wireframes(mut commands: Commands, query: Query<Entity, With<Wirefram
6061
#[reflect(Component, Default)]
6162
pub struct Wireframe;
6263

63-
#[derive(Debug, Clone, Default, ExtractResource)]
64+
#[derive(Debug, Clone, Default, ExtractResource, Reflect)]
65+
#[reflect(Resource)]
6466
pub struct WireframeConfig {
6567
/// Whether to show wireframes for all meshes. If `false`, only meshes with a [Wireframe] component will be rendered.
6668
pub global: bool,

crates/bevy_render/src/view/mod.rs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,14 +21,16 @@ use crate::{
2121
use bevy_app::{App, Plugin};
2222
use bevy_ecs::prelude::*;
2323
use bevy_math::{Mat4, Vec3};
24+
use bevy_reflect::Reflect;
2425
use bevy_transform::components::GlobalTransform;
2526
use bevy_utils::HashMap;
2627

2728
pub struct ViewPlugin;
2829

2930
impl Plugin for ViewPlugin {
3031
fn build(&self, app: &mut App) {
31-
app.init_resource::<Msaa>()
32+
app.register_type::<Msaa>()
33+
.init_resource::<Msaa>()
3234
// NOTE: windows.is_changed() handles cases where a window was resized
3335
.add_plugin(ExtractResourcePlugin::<Msaa>::default())
3436
.add_plugin(VisibilityPlugin);
@@ -45,7 +47,6 @@ impl Plugin for ViewPlugin {
4547
}
4648
}
4749

48-
#[derive(Clone, ExtractResource)]
4950
/// Configuration resource for [Multi-Sample Anti-Aliasing](https://en.wikipedia.org/wiki/Multisample_anti-aliasing).
5051
///
5152
/// # Example
@@ -56,6 +57,8 @@ impl Plugin for ViewPlugin {
5657
/// .insert_resource(Msaa { samples: 4 })
5758
/// .run();
5859
/// ```
60+
#[derive(Clone, ExtractResource, Reflect)]
61+
#[reflect(Resource)]
5962
pub struct Msaa {
6063
/// The number of samples to run for Multi-Sample Anti-Aliasing. Higher numbers result in
6164
/// smoother edges.

0 commit comments

Comments
 (0)