Skip to content

Commit

Permalink
Extract resources into their target location (bevyengine#5271)
Browse files Browse the repository at this point in the history
# Objective

- Extracting resources currently always uses commands, which requires *at least* one additional move of the extracted value, as well as dynamic dispatch.
- Addresses bevyengine#4402 (comment)

## Solution

- Write the resource into a `ResMut<R>` directly.
- Fall-back to commands if the resource hasn't been added yet.
  • Loading branch information
DJMcNab authored and james7132 committed Oct 28, 2022
1 parent 4fd6969 commit d312566
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 5 deletions.
1 change: 1 addition & 0 deletions crates/bevy_render/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ bevy_core = { path = "../bevy_core", version = "0.8.0-dev" }
bevy_derive = { path = "../bevy_derive", version = "0.8.0-dev" }
bevy_ecs = { path = "../bevy_ecs", version = "0.8.0-dev" }
bevy_encase_derive = { path = "../bevy_encase_derive", version = "0.8.0-dev" }
bevy_log = { path = "../bevy_log", version = "0.8.0-dev" }
bevy_math = { path = "../bevy_math", version = "0.8.0-dev" }
bevy_mikktspace = { path = "../bevy_mikktspace", version = "0.8.0-dev" }
bevy_reflect = { path = "../bevy_reflect", version = "0.8.0-dev", features = ["bevy"] }
Expand Down
24 changes: 19 additions & 5 deletions crates/bevy_render/src/extract_resource.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::marker::PhantomData;

use bevy_app::{App, Plugin};
use bevy_ecs::system::{Commands, Res, Resource};
use bevy_ecs::system::{Commands, Local, Res, ResMut, Resource};
pub use bevy_render_macros::ExtractResource;

use crate::{Extract, RenderApp, RenderStage};
Expand Down Expand Up @@ -38,12 +38,26 @@ impl<R: ExtractResource> Plugin for ExtractResourcePlugin<R> {
}

/// This system extracts the resource of the corresponding [`Resource`] type
/// by cloning it.
pub fn extract_resource<R: ExtractResource>(
mut commands: Commands,
resource: Extract<Res<R::Source>>,
main_resource: Extract<Res<R::Source>>,
target_resource: Option<ResMut<R>>,
#[cfg(debug_assertions)] mut has_warned_on_remove: Local<bool>,
) {
if resource.is_changed() {
commands.insert_resource(R::extract_resource(&*resource));
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));
}
}

0 comments on commit d312566

Please sign in to comment.