alter_mesh/alter_mesh.rs
1//! Shows how to modify mesh assets after spawning.
2
3use bevy::{
4 gltf::GltfLoaderSettings,
5 input::common_conditions::input_just_pressed,
6 prelude::*,
7 render::{mesh::VertexAttributeValues, render_asset::RenderAssetUsages},
8};
9
10fn main() {
11 App::new()
12 .add_plugins(DefaultPlugins)
13 .add_systems(Startup, (setup, spawn_text))
14 .add_systems(
15 Update,
16 alter_handle.run_if(input_just_pressed(KeyCode::Space)),
17 )
18 .add_systems(
19 Update,
20 alter_mesh.run_if(input_just_pressed(KeyCode::Enter)),
21 )
22 .run();
23}
24
25#[derive(Component, Debug)]
26enum Shape {
27 Cube,
28 Sphere,
29}
30
31impl Shape {
32 fn get_model_path(&self) -> String {
33 match self {
34 Shape::Cube => "models/cube/cube.gltf".into(),
35 Shape::Sphere => "models/sphere/sphere.gltf".into(),
36 }
37 }
38
39 fn set_next_variant(&mut self) {
40 *self = match self {
41 Shape::Cube => Shape::Sphere,
42 Shape::Sphere => Shape::Cube,
43 }
44 }
45}
46
47#[derive(Component, Debug)]
48struct Left;
49
50fn setup(
51 mut commands: Commands,
52 asset_server: Res<AssetServer>,
53 mut materials: ResMut<Assets<StandardMaterial>>,
54) {
55 let left_shape = Shape::Cube;
56 let right_shape = Shape::Cube;
57
58 // In normal use, you can call `asset_server.load`, however see below for an explanation of
59 // `RenderAssetUsages`.
60 let left_shape_model = asset_server.load_with_settings(
61 GltfAssetLabel::Primitive {
62 mesh: 0,
63 // This field stores an index to this primitive in its parent mesh. In this case, we
64 // want the first one. You might also have seen the syntax:
65 //
66 // models/cube/cube.gltf#Scene0
67 //
68 // which accomplishes the same thing.
69 primitive: 0,
70 }
71 .from_asset(left_shape.get_model_path()),
72 // `RenderAssetUsages::all()` is already the default, so the line below could be omitted.
73 // It's helpful to know it exists, however.
74 //
75 // `RenderAssetUsages` tell Bevy whether to keep the data around:
76 // - for the GPU (`RenderAssetUsages::RENDER_WORLD`),
77 // - for the CPU (`RenderAssetUsages::MAIN_WORLD`),
78 // - or both.
79 // `RENDER_WORLD` is necessary to render the mesh, `MAIN_WORLD` is necessary to inspect
80 // and modify the mesh (via `ResMut<Assets<Mesh>>`).
81 //
82 // Since most games will not need to modify meshes at runtime, many developers opt to pass
83 // only `RENDER_WORLD`. This is more memory efficient, as we don't need to keep the mesh in
84 // RAM. For this example however, this would not work, as we need to inspect and modify the
85 // mesh at runtime.
86 |settings: &mut GltfLoaderSettings| settings.load_meshes = RenderAssetUsages::all(),
87 );
88
89 // Here, we rely on the default loader settings to achieve a similar result to the above.
90 let right_shape_model = asset_server.load(
91 GltfAssetLabel::Primitive {
92 mesh: 0,
93 primitive: 0,
94 }
95 .from_asset(right_shape.get_model_path()),
96 );
97
98 // Add a material asset directly to the materials storage
99 let material_handle = materials.add(StandardMaterial {
100 base_color: Color::srgb(0.6, 0.8, 0.6),
101 ..default()
102 });
103
104 commands.spawn((
105 Left,
106 Name::new("Left Shape"),
107 Mesh3d(left_shape_model),
108 MeshMaterial3d(material_handle.clone()),
109 Transform::from_xyz(-3.0, 0.0, 0.0),
110 left_shape,
111 ));
112
113 commands.spawn((
114 Name::new("Right Shape"),
115 Mesh3d(right_shape_model),
116 MeshMaterial3d(material_handle),
117 Transform::from_xyz(3.0, 0.0, 0.0),
118 right_shape,
119 ));
120
121 commands.spawn((
122 Name::new("Point Light"),
123 PointLight::default(),
124 Transform::from_xyz(4.0, 5.0, 4.0),
125 ));
126
127 commands.spawn((
128 Name::new("Camera"),
129 Camera3d::default(),
130 Transform::from_xyz(0.0, 3.0, 20.0).looking_at(Vec3::ZERO, Vec3::Y),
131 ));
132}
133
134fn spawn_text(mut commands: Commands) {
135 commands.spawn((
136 Name::new("Instructions"),
137 Text::new(
138 "Space: swap meshes by mutating a Handle<Mesh>\n\
139 Return: mutate the mesh itself, changing all copies of it",
140 ),
141 Node {
142 position_type: PositionType::Absolute,
143 top: Val::Px(12.),
144 left: Val::Px(12.),
145 ..default()
146 },
147 ));
148}
149
150fn alter_handle(
151 asset_server: Res<AssetServer>,
152 mut right_shape: Query<(&mut Mesh3d, &mut Shape), Without<Left>>,
153) {
154 // Mesh handles, like other parts of the ECS, can be queried as mutable and modified at
155 // runtime. We only spawned one shape without the `Left` marker component.
156 let Ok((mut mesh, mut shape)) = right_shape.get_single_mut() else {
157 return;
158 };
159
160 // Switch to a new Shape variant
161 shape.set_next_variant();
162
163 // Modify the handle associated with the Shape on the right side. Note that we will only
164 // have to load the same path from storage media once: repeated attempts will re-use the
165 // asset.
166 mesh.0 = asset_server.load(
167 GltfAssetLabel::Primitive {
168 mesh: 0,
169 primitive: 0,
170 }
171 .from_asset(shape.get_model_path()),
172 );
173}
174
175fn alter_mesh(
176 mut is_mesh_scaled: Local<bool>,
177 left_shape: Query<&Mesh3d, With<Left>>,
178 mut meshes: ResMut<Assets<Mesh>>,
179) {
180 // It's convenient to retrieve the asset handle stored with the shape on the left. However,
181 // we could just as easily have retained this in a resource or a dedicated component.
182 let Ok(handle) = left_shape.get_single() else {
183 return;
184 };
185
186 // Obtain a mutable reference to the Mesh asset.
187 let Some(mesh) = meshes.get_mut(handle) else {
188 return;
189 };
190
191 // Now we can directly manipulate vertices on the mesh. Here, we're just scaling in and out
192 // for demonstration purposes. This will affect all entities currently using the asset.
193 //
194 // To do this, we need to grab the stored attributes of each vertex. `Float32x3` just describes
195 // the format in which the attributes will be read: each position consists of an array of three
196 // f32 corresponding to x, y, and z.
197 //
198 // `ATTRIBUTE_POSITION` is a constant indicating that we want to know where the vertex is
199 // located in space (as opposed to which way its normal is facing, vertex color, or other
200 // details).
201 if let Some(VertexAttributeValues::Float32x3(positions)) =
202 mesh.attribute_mut(Mesh::ATTRIBUTE_POSITION)
203 {
204 // Check a Local value (which only this system can make use of) to determine if we're
205 // currently scaled up or not.
206 let scale_factor = if *is_mesh_scaled { 0.5 } else { 2.0 };
207
208 for position in positions.iter_mut() {
209 // Apply the scale factor to each of x, y, and z.
210 position[0] *= scale_factor;
211 position[1] *= scale_factor;
212 position[2] *= scale_factor;
213 }
214
215 // Flip the local value to reverse the behavior next time the key is pressed.
216 *is_mesh_scaled = !*is_mesh_scaled;
217 }
218}