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
use std::marker::PhantomData;
use bevy_app::{App, Plugin};
#[cfg(debug_assertions)]
use bevy_ecs::system::Local;
use bevy_ecs::system::{Commands, Res, ResMut, Resource};
pub use bevy_render_macros::ExtractResource;
use crate::{Extract, RenderApp, RenderStage};
pub trait ExtractResource: Resource {
type Source: Resource;
fn extract_resource(source: &Self::Source) -> Self;
}
pub struct ExtractResourcePlugin<R: ExtractResource>(PhantomData<R>);
impl<R: ExtractResource> Default for ExtractResourcePlugin<R> {
fn default() -> Self {
Self(PhantomData)
}
}
impl<R: ExtractResource> Plugin for ExtractResourcePlugin<R> {
fn build(&self, app: &mut App) {
if let Ok(render_app) = app.get_sub_app_mut(RenderApp) {
render_app.add_system_to_stage(RenderStage::Extract, extract_resource::<R>);
}
}
}
pub fn extract_resource<R: ExtractResource>(
mut commands: Commands,
main_resource: Extract<Res<R::Source>>,
target_resource: Option<ResMut<R>>,
#[cfg(debug_assertions)] mut has_warned_on_remove: Local<bool>,
) {
if let Some(mut target_resource) = target_resource {
if main_resource.is_changed() {
*target_resource = R::extract_resource(&main_resource);
}
} else {
#[cfg(debug_assertions)]
if !main_resource.is_added() && !*has_warned_on_remove {
*has_warned_on_remove = true;
bevy_log::warn!(
"Removing resource {} from render world not expected, adding using `Commands`.
This may decrease performance",
std::any::type_name::<R>()
);
}
commands.insert_resource(R::extract_resource(&main_resource));
}
}