Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/crates/bevy_render/src/extract_resource.rs
6595 views
1
use core::marker::PhantomData;
2
3
use bevy_app::{App, Plugin};
4
use bevy_ecs::prelude::*;
5
pub use bevy_render_macros::ExtractResource;
6
use bevy_utils::once;
7
8
use crate::{Extract, ExtractSchedule, RenderApp};
9
10
/// Describes how a resource gets extracted for rendering.
11
///
12
/// Therefore the resource is transferred from the "main world" into the "render world"
13
/// in the [`ExtractSchedule`] step.
14
pub trait ExtractResource: Resource {
15
type Source: Resource;
16
17
/// Defines how the resource is transferred into the "render world".
18
fn extract_resource(source: &Self::Source) -> Self;
19
}
20
21
/// This plugin extracts the resources into the "render world".
22
///
23
/// Therefore it sets up the[`ExtractSchedule`] step
24
/// for the specified [`Resource`].
25
pub struct ExtractResourcePlugin<R: ExtractResource>(PhantomData<R>);
26
27
impl<R: ExtractResource> Default for ExtractResourcePlugin<R> {
28
fn default() -> Self {
29
Self(PhantomData)
30
}
31
}
32
33
impl<R: ExtractResource> Plugin for ExtractResourcePlugin<R> {
34
fn build(&self, app: &mut App) {
35
if let Some(render_app) = app.get_sub_app_mut(RenderApp) {
36
render_app.add_systems(ExtractSchedule, extract_resource::<R>);
37
} else {
38
once!(tracing::error!(
39
"Render app did not exist when trying to add `extract_resource` for <{}>.",
40
core::any::type_name::<R>()
41
));
42
}
43
}
44
}
45
46
/// This system extracts the resource of the corresponding [`Resource`] type
47
pub fn extract_resource<R: ExtractResource>(
48
mut commands: Commands,
49
main_resource: Extract<Option<Res<R::Source>>>,
50
target_resource: Option<ResMut<R>>,
51
) {
52
if let Some(main_resource) = main_resource.as_ref() {
53
if let Some(mut target_resource) = target_resource {
54
if main_resource.is_changed() {
55
*target_resource = R::extract_resource(main_resource);
56
}
57
} else {
58
#[cfg(debug_assertions)]
59
if !main_resource.is_added() {
60
once!(tracing::warn!(
61
"Removing resource {} from render world not expected, adding using `Commands`.
62
This may decrease performance",
63
core::any::type_name::<R>()
64
));
65
}
66
67
commands.insert_resource(R::extract_resource(main_resource));
68
}
69
}
70
}
71
72