pub struct ResMut<'w, T>{ /* private fields */ }
Expand description
Unique mutable borrow of a Resource
.
See the Resource
documentation for usage.
If you need a shared borrow, use Res
instead.
§Panics
Panics when used as a SystemParam
if the resource does not exist.
Use Option<ResMut<T>>
instead if the resource might not always exist.
Implementations§
source§impl<'w, T> ResMut<'w, T>
impl<'w, T> ResMut<'w, T>
sourcepub fn into_inner(self) -> &'w mut T
pub fn into_inner(self) -> &'w mut T
Consume self
and return a mutable reference to the
contained value while marking self
as “changed”.
Examples found in repository?
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
fn scheduled_spawner(
mut commands: Commands,
args: Res<Args>,
windows: Query<&Window>,
mut scheduled: ResMut<BirdScheduled>,
mut counter: ResMut<BevyCounter>,
bird_resources: ResMut<BirdResources>,
) {
let window = windows.single();
if scheduled.waves > 0 {
let bird_resources = bird_resources.into_inner();
spawn_birds(
&mut commands,
args.into_inner(),
&window.resolution,
&mut counter,
scheduled.per_wave,
bird_resources,
None,
scheduled.waves - 1,
);
scheduled.waves -= 1;
}
}
#[derive(Resource)]
struct BirdResources {
textures: Vec<Handle<Image>>,
materials: Vec<Handle<ColorMaterial>>,
quad: Mesh2dHandle,
color_rng: StdRng,
material_rng: StdRng,
velocity_rng: StdRng,
transform_rng: StdRng,
}
#[derive(Component)]
struct StatsText;
#[allow(clippy::too_many_arguments)]
fn setup(
mut commands: Commands,
args: Res<Args>,
asset_server: Res<AssetServer>,
mut meshes: ResMut<Assets<Mesh>>,
material_assets: ResMut<Assets<ColorMaterial>>,
images: ResMut<Assets<Image>>,
windows: Query<&Window>,
counter: ResMut<BevyCounter>,
) {
warn!(include_str!("warning_string.txt"));
let args = args.into_inner();
let images = images.into_inner();
let mut textures = Vec::with_capacity(args.material_texture_count.max(1));
if matches!(args.mode, Mode::Sprite) || args.material_texture_count > 0 {
textures.push(asset_server.load("branding/icon.png"));
}
init_textures(&mut textures, args, images);
let material_assets = material_assets.into_inner();
let materials = init_materials(args, &textures, material_assets);
let mut bird_resources = BirdResources {
textures,
materials,
quad: meshes
.add(Rectangle::from_size(Vec2::splat(BIRD_TEXTURE_SIZE as f32)))
.into(),
color_rng: StdRng::seed_from_u64(42),
material_rng: StdRng::seed_from_u64(42),
velocity_rng: StdRng::seed_from_u64(42),
transform_rng: StdRng::seed_from_u64(42),
};
let text_section = move |color, value: &str| {
TextSection::new(
value,
TextStyle {
font_size: 40.0,
color,
..default()
},
)
};
commands.spawn(Camera2dBundle::default());
commands
.spawn(NodeBundle {
style: Style {
position_type: PositionType::Absolute,
padding: UiRect::all(Val::Px(5.0)),
..default()
},
z_index: ZIndex::Global(i32::MAX),
background_color: Color::BLACK.with_a(0.75).into(),
..default()
})
.with_children(|c| {
c.spawn((
TextBundle::from_sections([
text_section(Color::GREEN, "Bird Count: "),
text_section(Color::CYAN, ""),
text_section(Color::GREEN, "\nFPS (raw): "),
text_section(Color::CYAN, ""),
text_section(Color::GREEN, "\nFPS (SMA): "),
text_section(Color::CYAN, ""),
text_section(Color::GREEN, "\nFPS (EMA): "),
text_section(Color::CYAN, ""),
]),
StatsText,
));
});
let mut scheduled = BirdScheduled {
per_wave: args.per_wave,
waves: args.waves,
};
if args.benchmark {
let counter = counter.into_inner();
for wave in (0..scheduled.waves).rev() {
spawn_birds(
&mut commands,
args,
&windows.single().resolution,
counter,
scheduled.per_wave,
&mut bird_resources,
Some(wave),
wave,
);
}
scheduled.waves = 0;
}
commands.insert_resource(bird_resources);
commands.insert_resource(scheduled);
}
#[allow(clippy::too_many_arguments)]
fn mouse_handler(
mut commands: Commands,
args: Res<Args>,
time: Res<Time>,
mouse_button_input: Res<ButtonInput<MouseButton>>,
windows: Query<&Window>,
bird_resources: ResMut<BirdResources>,
mut counter: ResMut<BevyCounter>,
mut rng: Local<Option<StdRng>>,
mut wave: Local<usize>,
) {
if rng.is_none() {
*rng = Some(StdRng::seed_from_u64(42));
}
let rng = rng.as_mut().unwrap();
let window = windows.single();
if mouse_button_input.just_released(MouseButton::Left) {
counter.color = Color::rgb_linear(rng.gen(), rng.gen(), rng.gen());
}
if mouse_button_input.pressed(MouseButton::Left) {
let spawn_count = (BIRDS_PER_SECOND as f64 * time.delta_seconds_f64()) as usize;
spawn_birds(
&mut commands,
args.into_inner(),
&window.resolution,
&mut counter,
spawn_count,
bird_resources.into_inner(),
None,
*wave,
);
*wave += 1;
}
}
More examples
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
fn setup(
mut commands: Commands,
args: Res<Args>,
mut meshes: ResMut<Assets<Mesh>>,
material_assets: ResMut<Assets<StandardMaterial>>,
images: ResMut<Assets<Image>>,
) {
warn!(include_str!("warning_string.txt"));
let args = args.into_inner();
let images = images.into_inner();
let material_assets = material_assets.into_inner();
let mesh = meshes.add(Cuboid::default());
let material_textures = init_textures(args, images);
let materials = init_materials(args, &material_textures, material_assets);
let mut material_rng = StdRng::seed_from_u64(42);
match args.layout {
Layout::Sphere => {
// NOTE: This pattern is good for testing performance of culling as it provides roughly
// the same number of visible meshes regardless of the viewing angle.
const N_POINTS: usize = WIDTH * HEIGHT * 4;
// NOTE: f64 is used to avoid precision issues that produce visual artifacts in the distribution
let radius = WIDTH as f64 * 2.5;
let golden_ratio = 0.5f64 * (1.0f64 + 5.0f64.sqrt());
for i in 0..N_POINTS {
let spherical_polar_theta_phi =
fibonacci_spiral_on_sphere(golden_ratio, i, N_POINTS);
let unit_sphere_p = spherical_polar_to_cartesian(spherical_polar_theta_phi);
commands.spawn(PbrBundle {
mesh: mesh.clone(),
material: materials.choose(&mut material_rng).unwrap().clone(),
transform: Transform::from_translation((radius * unit_sphere_p).as_vec3()),
..default()
});
}
// camera
commands.spawn(Camera3dBundle::default());
}
_ => {
// NOTE: This pattern is good for demonstrating that frustum culling is working correctly
// as the number of visible meshes rises and falls depending on the viewing angle.
for x in 0..WIDTH {
for y in 0..HEIGHT {
// introduce spaces to break any kind of moiré pattern
if x % 10 == 0 || y % 10 == 0 {
continue;
}
// cube
commands.spawn(PbrBundle {
mesh: mesh.clone(),
material: materials.choose(&mut material_rng).unwrap().clone(),
transform: Transform::from_xyz((x as f32) * 2.5, (y as f32) * 2.5, 0.0),
..default()
});
commands.spawn(PbrBundle {
mesh: mesh.clone(),
material: materials.choose(&mut material_rng).unwrap().clone(),
transform: Transform::from_xyz(
(x as f32) * 2.5,
HEIGHT as f32 * 2.5,
(y as f32) * 2.5,
),
..default()
});
commands.spawn(PbrBundle {
mesh: mesh.clone(),
material: materials.choose(&mut material_rng).unwrap().clone(),
transform: Transform::from_xyz((x as f32) * 2.5, 0.0, (y as f32) * 2.5),
..default()
});
commands.spawn(PbrBundle {
mesh: mesh.clone(),
material: materials.choose(&mut material_rng).unwrap().clone(),
transform: Transform::from_xyz(0.0, (x as f32) * 2.5, (y as f32) * 2.5),
..default()
});
}
}
// camera
commands.spawn(Camera3dBundle {
transform: Transform::from_xyz(WIDTH as f32, HEIGHT as f32, WIDTH as f32),
..default()
});
}
}
commands.spawn(DirectionalLightBundle::default());
}
sourcepub fn reborrow(&mut self) -> Mut<'_, T>
pub fn reborrow(&mut self) -> Mut<'_, T>
Returns a Mut<>
with a smaller lifetime.
This is useful if you have &mut ResMut <T>
, but you need a Mut<T>
.
sourcepub fn map_unchanged<U>(self, f: impl FnOnce(&mut T) -> &mut U) -> Mut<'w, U>where
U: ?Sized,
pub fn map_unchanged<U>(self, f: impl FnOnce(&mut T) -> &mut U) -> Mut<'w, U>where
U: ?Sized,
Maps to an inner value by applying a function to the contained reference, without flagging a change.
You should never modify the argument passed to the closure – if you want to modify the data
without flagging a change, consider using DetectChangesMut::bypass_change_detection
to make your intent explicit.
// When run, zeroes the translation of every entity.
fn reset_positions(mut transforms: Query<&mut Transform>) {
for transform in &mut transforms {
// We pinky promise not to modify `t` within the closure.
// Breaking this promise will result in logic errors, but will never cause undefined behavior.
let mut translation = transform.map_unchanged(|t| &mut t.translation);
// Only reset the translation if it isn't already zero;
translation.set_if_neq(Vec2::ZERO);
}
}
Trait Implementations§
source§impl<'w, T> DetectChanges for ResMut<'w, T>
impl<'w, T> DetectChanges for ResMut<'w, T>
source§fn is_changed(&self) -> bool
fn is_changed(&self) -> bool
true
if this value was added or mutably dereferenced
either since the last time the system ran or, if the system never ran,
since the beginning of the program. Read moresource§fn last_changed(&self) -> Tick
fn last_changed(&self) -> Tick
source§impl<'w, T> DetectChangesMut for ResMut<'w, T>
impl<'w, T> DetectChangesMut for ResMut<'w, T>
source§fn set_changed(&mut self)
fn set_changed(&mut self)
source§fn set_last_changed(&mut self, last_changed: Tick)
fn set_last_changed(&mut self, last_changed: Tick)
source§fn bypass_change_detection(
&mut self
) -> &mut <ResMut<'w, T> as DetectChangesMut>::Inner
fn bypass_change_detection( &mut self ) -> &mut <ResMut<'w, T> as DetectChangesMut>::Inner
source§impl<'w, 'a, T> IntoIterator for &'a ResMut<'w, T>
impl<'w, 'a, T> IntoIterator for &'a ResMut<'w, T>
§type Item = <&'a T as IntoIterator>::Item
type Item = <&'a T as IntoIterator>::Item
§type IntoIter = <&'a T as IntoIterator>::IntoIter
type IntoIter = <&'a T as IntoIterator>::IntoIter
source§impl<'w, 'a, T> IntoIterator for &'a mut ResMut<'w, T>
impl<'w, 'a, T> IntoIterator for &'a mut ResMut<'w, T>
§type Item = <&'a mut T as IntoIterator>::Item
type Item = <&'a mut T as IntoIterator>::Item
§type IntoIter = <&'a mut T as IntoIterator>::IntoIter
type IntoIter = <&'a mut T as IntoIterator>::IntoIter
source§impl<'a, T> SystemParam for ResMut<'a, T>where
T: Resource,
impl<'a, T> SystemParam for ResMut<'a, T>where
T: Resource,
§type State = ComponentId
type State = ComponentId
§type Item<'w, 's> = ResMut<'w, T>
type Item<'w, 's> = ResMut<'w, T>
Self
, instantiated with new lifetimes. Read moresource§fn init_state(
world: &mut World,
system_meta: &mut SystemMeta
) -> <ResMut<'a, T> as SystemParam>::State
fn init_state( world: &mut World, system_meta: &mut SystemMeta ) -> <ResMut<'a, T> as SystemParam>::State
World
access used by this SystemParam
and creates a new instance of this param’s State
.source§unsafe fn get_param<'w, 's>(
_: &'s mut <ResMut<'a, T> as SystemParam>::State,
system_meta: &SystemMeta,
world: UnsafeWorldCell<'w>,
change_tick: Tick
) -> <ResMut<'a, T> as SystemParam>::Item<'w, 's>
unsafe fn get_param<'w, 's>( _: &'s mut <ResMut<'a, T> as SystemParam>::State, system_meta: &SystemMeta, world: UnsafeWorldCell<'w>, change_tick: Tick ) -> <ResMut<'a, T> as SystemParam>::Item<'w, 's>
SystemParamFunction
. Read moresource§fn new_archetype(
_state: &mut Self::State,
_archetype: &Archetype,
_system_meta: &mut SystemMeta
)
fn new_archetype( _state: &mut Self::State, _archetype: &Archetype, _system_meta: &mut SystemMeta )
Archetype
, registers the components accessed by this SystemParam
(if applicable).source§fn apply(state: &mut Self::State, system_meta: &SystemMeta, world: &mut World)
fn apply(state: &mut Self::State, system_meta: &SystemMeta, world: &mut World)
SystemParam
’s state.
This is used to apply Commands
during apply_deferred
.Auto Trait Implementations§
impl<'w, T> Freeze for ResMut<'w, T>
impl<'w, T> RefUnwindSafe for ResMut<'w, T>
impl<'w, T> Send for ResMut<'w, T>
impl<'w, T> Sync for ResMut<'w, T>
impl<'w, T> Unpin for ResMut<'w, T>
impl<'w, T> !UnwindSafe for ResMut<'w, T>
Blanket Implementations§
source§impl<T, U> AsBindGroupShaderType<U> for T
impl<T, U> AsBindGroupShaderType<U> for T
source§fn as_bind_group_shader_type(&self, _images: &RenderAssets<Image>) -> U
fn as_bind_group_shader_type(&self, _images: &RenderAssets<Image>) -> U
T
ShaderType
for self
. When used in AsBindGroup
derives, it is safe to assume that all images in self
exist.source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
source§impl<T> Downcast for Twhere
T: Any,
impl<T> Downcast for Twhere
T: Any,
source§fn into_any(self: Box<T>) -> Box<dyn Any>
fn into_any(self: Box<T>) -> Box<dyn Any>
Box<dyn Trait>
(where Trait: Downcast
) to Box<dyn Any>
. Box<dyn Any>
can
then be further downcast
into Box<ConcreteType>
where ConcreteType
implements Trait
.source§fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>
Rc<Trait>
(where Trait: Downcast
) to Rc<Any>
. Rc<Any>
can then be
further downcast
into Rc<ConcreteType>
where ConcreteType
implements Trait
.source§fn as_any(&self) -> &(dyn Any + 'static)
fn as_any(&self) -> &(dyn Any + 'static)
&Trait
(where Trait: Downcast
) to &Any
. This is needed since Rust cannot
generate &Any
’s vtable from &Trait
’s.source§fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
fn as_any_mut(&mut self) -> &mut (dyn Any + 'static)
&mut Trait
(where Trait: Downcast
) to &Any
. This is needed since Rust cannot
generate &mut Any
’s vtable from &mut Trait
’s.