alter_sprite/alter_sprite.rs
1//! Shows how to modify texture assets after spawning.
2
3use bevy::{
4 asset::RenderAssetUsages, image::ImageLoaderSettings,
5 input::common_conditions::input_just_pressed, prelude::*,
6};
7
8fn main() {
9 App::new()
10 .add_plugins(DefaultPlugins)
11 .add_systems(Startup, (setup, spawn_text))
12 .add_systems(
13 Update,
14 alter_handle.run_if(input_just_pressed(KeyCode::Space)),
15 )
16 .add_systems(
17 Update,
18 alter_asset.run_if(input_just_pressed(KeyCode::Enter)),
19 )
20 .run();
21}
22
23#[derive(Component, Debug)]
24enum Bird {
25 Normal,
26 Logo,
27}
28
29impl Bird {
30 fn get_texture_path(&self) -> String {
31 match self {
32 Bird::Normal => "branding/bevy_bird_dark.png".into(),
33 Bird::Logo => "branding/bevy_logo_dark.png".into(),
34 }
35 }
36
37 fn set_next_variant(&mut self) {
38 *self = match self {
39 Bird::Normal => Bird::Logo,
40 Bird::Logo => Bird::Normal,
41 }
42 }
43}
44
45#[derive(Component, Debug)]
46struct Left;
47
48fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
49 let bird_left = Bird::Normal;
50 let bird_right = Bird::Normal;
51 commands.spawn(Camera2d);
52
53 let texture_left = asset_server
54 .load_builder()
55 .with_settings(
56 // `RenderAssetUsages::all()` is already the default, so the line below could be omitted.
57 // It's helpful to know it exists, however.
58 //
59 // `RenderAssetUsages` tell Bevy whether to keep the data around:
60 // - for the GPU (`RenderAssetUsages::RENDER_WORLD`),
61 // - for the CPU (`RenderAssetUsages::MAIN_WORLD`),
62 // - or both.
63 // `RENDER_WORLD` is necessary to render the image, `MAIN_WORLD` is necessary to inspect
64 // and modify the image (via `ResMut<Assets<Image>>`).
65 //
66 // Since most games will not need to modify textures at runtime, many developers opt to pass
67 // only `RENDER_WORLD`. This is more memory efficient, as we don't need to keep the image in
68 // RAM. For this example however, this would not work, as we need to inspect and modify the
69 // image at runtime.
70 |settings: &mut ImageLoaderSettings| settings.asset_usage = RenderAssetUsages::all(),
71 )
72 .load(bird_left.get_texture_path());
73
74 commands.spawn((
75 Name::new("Bird Left"),
76 // This marker component ensures we can easily find either of the Birds by using With and
77 // Without query filters.
78 Left,
79 Sprite::from_image(texture_left),
80 Transform::from_xyz(-200.0, 0.0, 0.0),
81 bird_left,
82 ));
83
84 commands.spawn((
85 Name::new("Bird Right"),
86 // In contrast to the above, here we rely on the default `RenderAssetUsages` loader setting
87 Sprite::from_image(asset_server.load(bird_right.get_texture_path())),
88 Transform::from_xyz(200.0, 0.0, 0.0),
89 bird_right,
90 ));
91}
92
93fn spawn_text(mut commands: Commands) {
94 commands.spawn((
95 Name::new("Instructions"),
96 Text::new(
97 "Space: swap the right sprite's image handle\n\
98 Return: modify the image Asset of the left sprite, affecting all uses of it",
99 ),
100 Node {
101 position_type: PositionType::Absolute,
102 top: px(12),
103 left: px(12),
104 ..default()
105 },
106 ));
107}
108
109fn alter_handle(
110 asset_server: Res<AssetServer>,
111 right_bird: Single<(&mut Bird, &mut Sprite), Without<Left>>,
112) {
113 // Image handles, like other parts of the ECS, can be queried as mutable and modified at
114 // runtime. We only spawned one bird without the `Left` marker component.
115 let (mut bird, mut sprite) = right_bird.into_inner();
116
117 // Switch to a new Bird variant
118 bird.set_next_variant();
119
120 // Modify the handle associated with the Bird on the right side. Note that we will only
121 // have to load the same path from storage media once: repeated attempts will re-use the
122 // asset.
123 sprite.image = asset_server.load(bird.get_texture_path());
124}
125
126fn alter_asset(mut images: ResMut<Assets<Image>>, left_bird: Single<&Sprite, With<Left>>) {
127 // Obtain a mutable reference to the Image asset.
128 let Some(mut image) = images.get_mut(&left_bird.image) else {
129 return;
130 };
131
132 for pixel in image.data.as_mut().unwrap() {
133 // Directly modify the asset data, which will affect all users of this asset. By
134 // contrast, mutating the handle (as we did above) affects only one copy. In this case,
135 // we'll just invert the colors, by way of demonstration. Notice that both uses of the
136 // asset show the change, not just the one on the left.
137 *pixel = 255 - *pixel;
138 }
139}