pub struct EntityCommands<'a> { /* private fields */ }
Expand description
A list of commands that will be run to modify an entity.
Implementations§
Source§impl<'a> EntityCommands<'a>
impl<'a> EntityCommands<'a>
Sourcepub fn id(&self) -> Entity
pub fn id(&self) -> Entity
Returns the Entity
id of the entity.
§Example
fn my_system(mut commands: Commands) {
let entity_id = commands.spawn_empty().id();
}
Examples found in repository?
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
fn setup_menu(mut commands: Commands) {
let button_entity = commands
.spawn(Node {
// center button
width: Val::Percent(100.),
height: Val::Percent(100.),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
..default()
})
.with_children(|parent| {
parent
.spawn((
Button,
Node {
width: Val::Px(150.),
height: Val::Px(65.),
// horizontally center child text
justify_content: JustifyContent::Center,
// vertically center child text
align_items: AlignItems::Center,
..default()
},
BackgroundColor(NORMAL_BUTTON),
))
.with_children(|parent| {
parent.spawn((
Text::new("Play"),
TextFont {
font_size: 33.0,
..default()
},
TextColor(Color::srgb(0.9, 0.9, 0.9)),
));
});
})
.id();
commands.insert_resource(MenuData { button_entity });
}
More examples
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
fn setup_menu(mut commands: Commands) {
let button_entity = commands
.spawn(Node {
// center button
width: Val::Percent(100.),
height: Val::Percent(100.),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
..default()
})
.with_children(|parent| {
parent
.spawn((
Button,
Node {
width: Val::Px(150.),
height: Val::Px(65.),
// horizontally center child text
justify_content: JustifyContent::Center,
// vertically center child text
align_items: AlignItems::Center,
..default()
},
BackgroundColor(NORMAL_BUTTON),
))
.with_children(|parent| {
parent.spawn((
Text::new("Play"),
TextFont {
font_size: 33.0,
..default()
},
TextColor(Color::srgb(0.9, 0.9, 0.9)),
));
});
})
.id();
commands.insert_resource(MenuData { button_entity });
}
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
fn setup(mut commands: Commands, asset_server: Res<AssetServer>) {
commands.spawn(Camera2d);
let texture = asset_server.load("branding/icon.png");
// Spawn a root entity with no parent
let parent = commands
.spawn((
Sprite::from_image(texture.clone()),
Transform::from_scale(Vec3::splat(0.75)),
))
// With that entity as a parent, run a lambda that spawns its children
.with_children(|parent| {
// parent is a ChildBuilder, which has a similar API to Commands
parent.spawn((
Transform::from_xyz(250.0, 0.0, 0.0).with_scale(Vec3::splat(0.75)),
Sprite {
image: texture.clone(),
color: BLUE.into(),
..default()
},
));
})
// Store parent entity for next sections
.id();
// Another way is to use the add_child function to add children after the parent
// entity has already been spawned.
let child = commands
.spawn((
Sprite {
image: texture,
color: LIME.into(),
..default()
},
Transform::from_xyz(0.0, 250.0, 0.0).with_scale(Vec3::splat(0.75)),
))
.id();
// Add child to the parent.
commands.entity(parent).add_child(child);
}
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
pub fn setup_menu(mut commands: Commands) {
let button_entity = commands
.spawn(Node {
// center button
width: Val::Percent(100.),
height: Val::Percent(100.),
justify_content: JustifyContent::Center,
align_items: AlignItems::Center,
..default()
})
.with_children(|parent| {
parent
.spawn((
Button,
Node {
width: Val::Px(150.),
height: Val::Px(65.),
// horizontally center child text
justify_content: JustifyContent::Center,
// vertically center child text
align_items: AlignItems::Center,
..default()
},
BackgroundColor(NORMAL_BUTTON),
))
.with_children(|parent| {
parent.spawn((
Text::new("Play"),
TextFont {
font_size: 33.0,
..default()
},
TextColor(Color::srgb(0.9, 0.9, 0.9)),
));
});
})
.id();
commands.insert_resource(MenuData { button_entity });
}
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 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
fn setup_contributor_selection(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut rng: ResMut<SharedRng>,
) {
let contribs = contributors_or_fallback();
let texture_handle = asset_server.load("branding/icon.png");
let mut contributor_selection = ContributorSelection {
order: Vec::with_capacity(contribs.len()),
idx: 0,
};
for (name, num_commits) in contribs {
let transform = Transform::from_xyz(
rng.gen_range(-400.0..400.0),
rng.gen_range(0.0..400.0),
rng.gen(),
);
let dir = rng.gen_range(-1.0..1.0);
let velocity = Vec3::new(dir * 500.0, 0.0, 0.0);
let hue = name_to_hue(&name);
// Some sprites should be flipped for variety
let flipped = rng.gen();
let entity = commands
.spawn((
Contributor {
name,
num_commits,
hue,
},
Velocity {
translation: velocity,
rotation: -dir * 5.0,
},
Sprite {
image: texture_handle.clone(),
custom_size: Some(Vec2::splat(SPRITE_SIZE)),
color: DESELECTED.with_hue(hue).into(),
flip_x: flipped,
..default()
},
transform,
))
.id();
contributor_selection.order.push(entity);
}
commands.insert_resource(contributor_selection);
}
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 66 67 68 69
fn setup_scene(mut commands: Commands, asset_server: Res<AssetServer>) {
// add entities to the world
commands.spawn(SceneRoot(
asset_server.load(GltfAssetLabel::Scene(0).from_asset("models/torus/torus.gltf")),
));
// light
commands.spawn((
DirectionalLight::default(),
Transform::from_xyz(3.0, 3.0, 3.0).looking_at(Vec3::ZERO, Vec3::Y),
));
let first_window_camera = commands
.spawn((
Camera3d::default(),
Transform::from_xyz(0.0, 0.0, 6.0).looking_at(Vec3::ZERO, Vec3::Y),
))
.id();
// Spawn a second window
let second_window = commands
.spawn(Window {
title: "Second window".to_owned(),
..default()
})
.id();
let second_window_camera = commands
.spawn((
Camera3d::default(),
Transform::from_xyz(6.0, 0.0, 0.0).looking_at(Vec3::ZERO, Vec3::Y),
Camera {
target: RenderTarget::Window(WindowRef::Entity(second_window)),
..default()
},
))
.id();
let node = Node {
position_type: PositionType::Absolute,
top: Val::Px(12.0),
left: Val::Px(12.0),
..default()
};
commands.spawn((
Text::new("First window"),
node.clone(),
// Since we are using multiple cameras, we need to specify which camera UI should be rendered to
TargetCamera(first_window_camera),
));
commands.spawn((
Text::new("Second window"),
node,
TargetCamera(second_window_camera),
));
}
- examples/ecs/observers.rs
- examples/animation/eased_motion.rs
- examples/window/monitor_info.rs
- examples/animation/animation_graph.rs
- examples/async_tasks/async_compute.rs
- examples/ui/render_ui_to_texture.rs
- examples/3d/irradiance_volumes.rs
- examples/stress_tests/transform_hierarchy.rs
- examples/ui/text_wrap_debug.rs
- examples/games/alien_cake_addict.rs
- examples/state/computed_states.rs
- examples/stress_tests/many_foxes.rs
- examples/3d/split_screen.rs
- examples/ui/display_and_visibility.rs
- examples/animation/custom_skinned_mesh.rs
- examples/3d/blend_modes.rs
- examples/animation/animated_transform.rs
- examples/ui/text_debug.rs
- examples/ui/borders.rs
Sourcepub fn reborrow(&mut self) -> EntityCommands<'_>
pub fn reborrow(&mut self) -> EntityCommands<'_>
Returns an EntityCommands
with a smaller lifetime.
This is useful if you have &mut EntityCommands
but you need EntityCommands
.
Sourcepub fn entry<T>(&mut self) -> EntityEntryCommands<'_, T>where
T: Component,
pub fn entry<T>(&mut self) -> EntityEntryCommands<'_, T>where
T: Component,
Get an EntityEntryCommands
for the Component
T
,
allowing you to modify it or insert it if it isn’t already present.
See also insert_if_new
, which lets you insert a Bundle
without overwriting it.
§Example
#[derive(Component)]
struct Level(u32);
fn level_up_system(mut commands: Commands, player: Res<PlayerEntity>) {
commands
.entity(player.entity)
.entry::<Level>()
// Modify the component if it exists
.and_modify(|mut lvl| lvl.0 += 1)
// Otherwise insert a default value
.or_insert(Level(0));
}
Sourcepub fn insert(&mut self, bundle: impl Bundle) -> &mut EntityCommands<'a>
pub fn insert(&mut self, bundle: impl Bundle) -> &mut EntityCommands<'a>
Adds a Bundle
of components to the entity.
This will overwrite any previous value(s) of the same component type.
See EntityCommands::insert_if_new
to keep the old value instead.
§Panics
The command will panic when applied if the associated entity does not exist.
To avoid a panic in this case, use the command Self::try_insert
instead.
§Example
#[derive(Component)]
struct Health(u32);
#[derive(Component)]
struct Strength(u32);
#[derive(Component)]
struct Defense(u32);
#[derive(Bundle)]
struct CombatBundle {
health: Health,
strength: Strength,
}
fn add_combat_stats_system(mut commands: Commands, player: Res<PlayerEntity>) {
commands
.entity(player.entity)
// You can insert individual components:
.insert(Defense(10))
// You can also insert pre-defined bundles of components:
.insert(CombatBundle {
health: Health(100),
strength: Strength(40),
})
// You can also insert tuples of components and bundles.
// This is equivalent to the calls above:
.insert((
Defense(10),
CombatBundle {
health: Health(100),
strength: Strength(40),
},
));
}
Examples found in repository?
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 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
fn spawn_sphere(commands: &mut Commands, assets: &ExampleAssets) {
commands
.spawn((
Mesh3d(assets.main_sphere.clone()),
MeshMaterial3d(assets.main_sphere_material.clone()),
Transform::from_xyz(0.0, SPHERE_SCALE, 0.0).with_scale(Vec3::splat(SPHERE_SCALE)),
))
.insert(MainObject);
}
fn spawn_voxel_cube_parent(commands: &mut Commands) {
commands.spawn((Visibility::Hidden, Transform::default(), VoxelCubeParent));
}
fn spawn_fox(commands: &mut Commands, assets: &ExampleAssets) {
commands.spawn((
SceneRoot(assets.fox.clone()),
Visibility::Hidden,
Transform::from_scale(Vec3::splat(FOX_SCALE)),
MainObject,
));
}
fn spawn_text(commands: &mut Commands, app_status: &AppStatus) {
commands.spawn((
app_status.create_text(),
Node {
position_type: PositionType::Absolute,
bottom: Val::Px(12.0),
left: Val::Px(12.0),
..default()
},
));
}
// A system that updates the help text.
fn update_text(mut text_query: Query<&mut Text>, app_status: Res<AppStatus>) {
for mut text in text_query.iter_mut() {
*text = app_status.create_text();
}
}
impl AppStatus {
// Constructs the help text at the bottom of the screen based on the
// application status.
fn create_text(&self) -> Text {
let irradiance_volume_help_text = if self.irradiance_volume_present {
DISABLE_IRRADIANCE_VOLUME_HELP_TEXT
} else {
ENABLE_IRRADIANCE_VOLUME_HELP_TEXT
};
let voxels_help_text = if self.voxels_visible {
HIDE_VOXELS_HELP_TEXT
} else {
SHOW_VOXELS_HELP_TEXT
};
let rotation_help_text = if self.rotating {
STOP_ROTATION_HELP_TEXT
} else {
START_ROTATION_HELP_TEXT
};
let switch_mesh_help_text = match self.model {
ExampleModel::Sphere => SWITCH_TO_FOX_HELP_TEXT,
ExampleModel::Fox => SWITCH_TO_SPHERE_HELP_TEXT,
};
format!(
"{CLICK_TO_MOVE_HELP_TEXT}\n\
{voxels_help_text}\n\
{irradiance_volume_help_text}\n\
{rotation_help_text}\n\
{switch_mesh_help_text}"
)
.into()
}
}
// Rotates the camera a bit every frame.
fn rotate_camera(
mut camera_query: Query<&mut Transform, With<Camera3d>>,
time: Res<Time>,
app_status: Res<AppStatus>,
) {
if !app_status.rotating {
return;
}
for mut transform in camera_query.iter_mut() {
transform.translation = Vec2::from_angle(ROTATION_SPEED * time.delta_secs())
.rotate(transform.translation.xz())
.extend(transform.translation.y)
.xzy();
transform.look_at(Vec3::ZERO, Vec3::Y);
}
}
// Toggles between the unskinned sphere model and the skinned fox model if the
// user requests it.
fn change_main_object(
keyboard: Res<ButtonInput<KeyCode>>,
mut app_status: ResMut<AppStatus>,
mut sphere_query: Query<&mut Visibility, (With<MainObject>, With<Mesh3d>, Without<SceneRoot>)>,
mut fox_query: Query<&mut Visibility, (With<MainObject>, With<SceneRoot>)>,
) {
if !keyboard.just_pressed(KeyCode::Tab) {
return;
}
let Some(mut sphere_visibility) = sphere_query.iter_mut().next() else {
return;
};
let Some(mut fox_visibility) = fox_query.iter_mut().next() else {
return;
};
match app_status.model {
ExampleModel::Sphere => {
*sphere_visibility = Visibility::Hidden;
*fox_visibility = Visibility::Visible;
app_status.model = ExampleModel::Fox;
}
ExampleModel::Fox => {
*sphere_visibility = Visibility::Visible;
*fox_visibility = Visibility::Hidden;
app_status.model = ExampleModel::Sphere;
}
}
}
impl Default for AppStatus {
fn default() -> Self {
Self {
irradiance_volume_present: true,
rotating: true,
model: ExampleModel::Sphere,
voxels_visible: false,
}
}
}
// Turns on and off the irradiance volume as requested by the user.
fn toggle_irradiance_volumes(
mut commands: Commands,
keyboard: Res<ButtonInput<KeyCode>>,
light_probe_query: Query<Entity, With<LightProbe>>,
mut app_status: ResMut<AppStatus>,
assets: Res<ExampleAssets>,
mut ambient_light: ResMut<AmbientLight>,
) {
if !keyboard.just_pressed(KeyCode::Space) {
return;
};
let Some(light_probe) = light_probe_query.iter().next() else {
return;
};
if app_status.irradiance_volume_present {
commands.entity(light_probe).remove::<IrradianceVolume>();
ambient_light.brightness = AMBIENT_LIGHT_BRIGHTNESS * IRRADIANCE_VOLUME_INTENSITY;
app_status.irradiance_volume_present = false;
} else {
commands.entity(light_probe).insert(IrradianceVolume {
voxels: assets.irradiance_volume.clone(),
intensity: IRRADIANCE_VOLUME_INTENSITY,
});
ambient_light.brightness = 0.0;
app_status.irradiance_volume_present = true;
}
}
fn toggle_rotation(keyboard: Res<ButtonInput<KeyCode>>, mut app_status: ResMut<AppStatus>) {
if keyboard.just_pressed(KeyCode::Enter) {
app_status.rotating = !app_status.rotating;
}
}
// Handles clicks on the plane that reposition the object.
fn handle_mouse_clicks(
buttons: Res<ButtonInput<MouseButton>>,
windows: Query<&Window, With<PrimaryWindow>>,
cameras: Query<(&Camera, &GlobalTransform)>,
mut main_objects: Query<&mut Transform, With<MainObject>>,
) {
if !buttons.pressed(MouseButton::Left) {
return;
}
let Some(mouse_position) = windows.iter().next().and_then(Window::cursor_position) else {
return;
};
let Some((camera, camera_transform)) = cameras.iter().next() else {
return;
};
// Figure out where the user clicked on the plane.
let Ok(ray) = camera.viewport_to_world(camera_transform, mouse_position) else {
return;
};
let Some(ray_distance) = ray.intersect_plane(Vec3::ZERO, InfinitePlane3d::new(Vec3::Y)) else {
return;
};
let plane_intersection = ray.origin + ray.direction.normalize() * ray_distance;
// Move all the main objeccts.
for mut transform in main_objects.iter_mut() {
transform.translation = vec3(
plane_intersection.x,
transform.translation.y,
plane_intersection.z,
);
}
}
impl FromWorld for ExampleAssets {
fn from_world(world: &mut World) -> Self {
let fox_animation =
world.load_asset(GltfAssetLabel::Animation(1).from_asset("models/animated/Fox.glb"));
let (fox_animation_graph, fox_animation_node) =
AnimationGraph::from_clip(fox_animation.clone());
ExampleAssets {
main_sphere: world.add_asset(Sphere::default().mesh().uv(32, 18)),
fox: world.load_asset(GltfAssetLabel::Scene(0).from_asset("models/animated/Fox.glb")),
main_sphere_material: world.add_asset(Color::from(SILVER)),
main_scene: world.load_asset(
GltfAssetLabel::Scene(0)
.from_asset("models/IrradianceVolumeExample/IrradianceVolumeExample.glb"),
),
irradiance_volume: world.load_asset("irradiance_volumes/Example.vxgi.ktx2"),
fox_animation_graph: world.add_asset(fox_animation_graph),
fox_animation_node,
voxel_cube: world.add_asset(Cuboid::default()),
// Just use a specular map for the skybox since it's not too blurry.
// In reality you wouldn't do this--you'd use a real skybox texture--but
// reusing the textures like this saves space in the Bevy repository.
skybox: world.load_asset("environment_maps/pisa_specular_rgb9e5_zstd.ktx2"),
}
}
}
// Plays the animation on the fox.
fn play_animations(
mut commands: Commands,
assets: Res<ExampleAssets>,
mut players: Query<(Entity, &mut AnimationPlayer), Without<AnimationGraphHandle>>,
) {
for (entity, mut player) in players.iter_mut() {
commands
.entity(entity)
.insert(AnimationGraphHandle(assets.fox_animation_graph.clone()));
player.play(assets.fox_animation_node).repeat();
}
}
fn create_cubes(
image_assets: Res<Assets<Image>>,
mut commands: Commands,
irradiance_volumes: Query<(&IrradianceVolume, &GlobalTransform)>,
voxel_cube_parents: Query<Entity, With<VoxelCubeParent>>,
voxel_cubes: Query<Entity, With<VoxelCube>>,
example_assets: Res<ExampleAssets>,
mut voxel_visualization_material_assets: ResMut<Assets<VoxelVisualizationMaterial>>,
) {
// If voxel cubes have already been spawned, don't do anything.
if !voxel_cubes.is_empty() {
return;
}
let Some(voxel_cube_parent) = voxel_cube_parents.iter().next() else {
return;
};
for (irradiance_volume, global_transform) in irradiance_volumes.iter() {
let Some(image) = image_assets.get(&irradiance_volume.voxels) else {
continue;
};
let resolution = image.texture_descriptor.size;
let voxel_cube_material = voxel_visualization_material_assets.add(ExtendedMaterial {
base: StandardMaterial::from(Color::from(RED)),
extension: VoxelVisualizationExtension {
irradiance_volume_info: VoxelVisualizationIrradianceVolumeInfo {
world_from_voxel: VOXEL_FROM_WORLD.inverse(),
voxel_from_world: VOXEL_FROM_WORLD,
resolution: uvec3(
resolution.width,
resolution.height,
resolution.depth_or_array_layers,
),
intensity: IRRADIANCE_VOLUME_INTENSITY,
},
},
});
let scale = vec3(
1.0 / resolution.width as f32,
1.0 / resolution.height as f32,
1.0 / resolution.depth_or_array_layers as f32,
);
// Spawn a cube for each voxel.
for z in 0..resolution.depth_or_array_layers {
for y in 0..resolution.height {
for x in 0..resolution.width {
let uvw = (uvec3(x, y, z).as_vec3() + 0.5) * scale - 0.5;
let pos = global_transform.transform_point(uvw);
let voxel_cube = commands
.spawn((
Mesh3d(example_assets.voxel_cube.clone()),
MeshMaterial3d(voxel_cube_material.clone()),
Transform::from_scale(Vec3::splat(VOXEL_CUBE_SCALE))
.with_translation(pos),
))
.insert(VoxelCube)
.insert(NotShadowCaster)
.id();
commands.entity(voxel_cube_parent).add_child(voxel_cube);
}
}
}
}
}
More examples
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
fn trigger_system(
mut commands: Commands,
query_a: Single<Entity, With<A>>,
query_b: Single<Entity, With<B>>,
input: Res<ButtonInput<KeyCode>>,
) {
if input.just_pressed(KeyCode::KeyA) {
let entity = *query_a;
commands.entity(entity).insert(Triggered);
}
if input.just_pressed(KeyCode::KeyB) {
let entity = *query_b;
commands.entity(entity).insert(Triggered);
}
}
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
fn add_environment_map_to_camera(
mut commands: Commands,
query: Query<Entity, Added<Camera3d>>,
cubemaps: Res<Cubemaps>,
) {
for camera_entity in query.iter() {
commands
.entity(camera_entity)
.insert(create_camera_environment_map_light(&cubemaps))
.insert(Skybox {
image: cubemaps.skybox.clone(),
brightness: 5000.0,
..default()
});
}
}
// A system that handles switching between different reflection modes.
fn change_reflection_type(
mut commands: Commands,
light_probe_query: Query<Entity, With<LightProbe>>,
camera_query: Query<Entity, With<Camera3d>>,
keyboard: Res<ButtonInput<KeyCode>>,
mut app_status: ResMut<AppStatus>,
cubemaps: Res<Cubemaps>,
) {
// Only do anything if space was pressed.
if !keyboard.just_pressed(KeyCode::Space) {
return;
}
// Switch reflection mode.
app_status.reflection_mode =
ReflectionMode::try_from((app_status.reflection_mode as u32 + 1) % 3).unwrap();
// Add or remove the light probe.
for light_probe in light_probe_query.iter() {
commands.entity(light_probe).despawn();
}
match app_status.reflection_mode {
ReflectionMode::None | ReflectionMode::EnvironmentMap => {}
ReflectionMode::ReflectionProbe => spawn_reflection_probe(&mut commands, &cubemaps),
}
// Add or remove the environment map from the camera.
for camera in camera_query.iter() {
match app_status.reflection_mode {
ReflectionMode::None => {
commands.entity(camera).remove::<EnvironmentMapLight>();
}
ReflectionMode::EnvironmentMap | ReflectionMode::ReflectionProbe => {
commands
.entity(camera)
.insert(create_camera_environment_map_light(&cubemaps));
}
}
}
}
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
fn screenshot_saving(
mut commands: Commands,
screenshot_saving: Query<Entity, With<Capturing>>,
windows: Query<Entity, With<Window>>,
) {
let Ok(window) = windows.get_single() else {
return;
};
match screenshot_saving.iter().count() {
0 => {
commands.entity(window).remove::<CursorIcon>();
}
x if x > 0 => {
commands
.entity(window)
.insert(CursorIcon::from(SystemCursorIcon::Progress));
}
_ => {}
}
}
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 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 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
fn spawn_cube(
commands: &mut Commands,
asset_server: &AssetServer,
meshes: &mut Assets<Mesh>,
standard_materials: &mut Assets<StandardMaterial>,
) {
commands
.spawn((
Mesh3d(meshes.add(Cuboid::new(1.0, 1.0, 1.0))),
MeshMaterial3d(standard_materials.add(StandardMaterial {
base_color: Color::from(WHITE),
base_color_texture: Some(asset_server.load("branding/icon.png")),
..default()
})),
Transform::from_xyz(0.0, 0.5, 0.0),
))
.insert(CubeModel);
}
// Spawns the flight helmet.
fn spawn_flight_helmet(commands: &mut Commands, asset_server: &AssetServer) {
commands.spawn((
SceneRoot(
asset_server
.load(GltfAssetLabel::Scene(0).from_asset("models/FlightHelmet/FlightHelmet.gltf")),
),
Transform::from_scale(Vec3::splat(2.5)),
FlightHelmetModel,
Visibility::Hidden,
));
}
// Spawns the water plane.
fn spawn_water(
commands: &mut Commands,
asset_server: &AssetServer,
meshes: &mut Assets<Mesh>,
water_materials: &mut Assets<ExtendedMaterial<StandardMaterial, Water>>,
) {
commands.spawn((
Mesh3d(meshes.add(Plane3d::new(Vec3::Y, Vec2::splat(1.0)))),
MeshMaterial3d(water_materials.add(ExtendedMaterial {
base: StandardMaterial {
base_color: BLACK.into(),
perceptual_roughness: 0.0,
..default()
},
extension: Water {
normals: asset_server.load_with_settings::<Image, ImageLoaderSettings>(
"textures/water_normals.png",
|settings| {
settings.is_srgb = false;
settings.sampler = ImageSampler::Descriptor(ImageSamplerDescriptor {
address_mode_u: ImageAddressMode::Repeat,
address_mode_v: ImageAddressMode::Repeat,
mag_filter: ImageFilterMode::Linear,
min_filter: ImageFilterMode::Linear,
..default()
});
},
),
// These water settings are just random values to create some
// variety.
settings: WaterSettings {
octave_vectors: [
vec4(0.080, 0.059, 0.073, -0.062),
vec4(0.153, 0.138, -0.149, -0.195),
],
octave_scales: vec4(1.0, 2.1, 7.9, 14.9) * 5.0,
octave_strengths: vec4(0.16, 0.18, 0.093, 0.044),
},
},
})),
Transform::from_scale(Vec3::splat(100.0)),
));
}
// Spawns the camera.
fn spawn_camera(commands: &mut Commands, asset_server: &AssetServer) {
// Create the camera. Add an environment map and skybox so the water has
// something interesting to reflect, other than the cube. Enable deferred
// rendering by adding depth and deferred prepasses. Turn on FXAA to make
// the scene look a little nicer. Finally, add screen space reflections.
commands
.spawn((
Camera3d::default(),
Transform::from_translation(vec3(-1.25, 2.25, 4.5)).looking_at(Vec3::ZERO, Vec3::Y),
Camera {
hdr: true,
..default()
},
Msaa::Off,
))
.insert(EnvironmentMapLight {
diffuse_map: asset_server.load("environment_maps/pisa_diffuse_rgb9e5_zstd.ktx2"),
specular_map: asset_server.load("environment_maps/pisa_specular_rgb9e5_zstd.ktx2"),
intensity: 5000.0,
..default()
})
.insert(Skybox {
image: asset_server.load("environment_maps/pisa_specular_rgb9e5_zstd.ktx2"),
brightness: 5000.0,
..default()
})
.insert(ScreenSpaceReflections::default())
.insert(Fxaa::default());
}
// Spawns the help text.
fn spawn_text(commands: &mut Commands, app_settings: &AppSettings) {
commands.spawn((
create_text(app_settings),
Node {
position_type: PositionType::Absolute,
bottom: Val::Px(12.0),
left: Val::Px(12.0),
..default()
},
));
}
// Creates or recreates the help text.
fn create_text(app_settings: &AppSettings) -> Text {
format!(
"{}\n{}\n{}",
match app_settings.displayed_model {
DisplayedModel::Cube => SWITCH_TO_FLIGHT_HELMET_HELP_TEXT,
DisplayedModel::FlightHelmet => SWITCH_TO_CUBE_HELP_TEXT,
},
if app_settings.ssr_on {
TURN_SSR_OFF_HELP_TEXT
} else {
TURN_SSR_ON_HELP_TEXT
},
MOVE_CAMERA_HELP_TEXT
)
.into()
}
impl MaterialExtension for Water {
fn deferred_fragment_shader() -> ShaderRef {
SHADER_ASSET_PATH.into()
}
}
/// Rotates the model on the Y axis a bit every frame.
fn rotate_model(
mut query: Query<&mut Transform, Or<(With<CubeModel>, With<FlightHelmetModel>)>>,
time: Res<Time>,
) {
for mut transform in query.iter_mut() {
transform.rotation = Quat::from_euler(EulerRot::XYZ, 0.0, time.elapsed_secs(), 0.0);
}
}
// Processes input related to camera movement.
fn move_camera(
keyboard_input: Res<ButtonInput<KeyCode>>,
mut mouse_wheel_input: EventReader<MouseWheel>,
mut cameras: Query<&mut Transform, With<Camera>>,
) {
let (mut distance_delta, mut theta_delta) = (0.0, 0.0);
// Handle keyboard events.
if keyboard_input.pressed(KeyCode::KeyW) {
distance_delta -= CAMERA_KEYBOARD_ZOOM_SPEED;
}
if keyboard_input.pressed(KeyCode::KeyS) {
distance_delta += CAMERA_KEYBOARD_ZOOM_SPEED;
}
if keyboard_input.pressed(KeyCode::KeyA) {
theta_delta += CAMERA_KEYBOARD_ORBIT_SPEED;
}
if keyboard_input.pressed(KeyCode::KeyD) {
theta_delta -= CAMERA_KEYBOARD_ORBIT_SPEED;
}
// Handle mouse events.
for mouse_wheel_event in mouse_wheel_input.read() {
distance_delta -= mouse_wheel_event.y * CAMERA_MOUSE_WHEEL_ZOOM_SPEED;
}
// Update transforms.
for mut camera_transform in cameras.iter_mut() {
let local_z = camera_transform.local_z().as_vec3().normalize_or_zero();
if distance_delta != 0.0 {
camera_transform.translation = (camera_transform.translation.length() + distance_delta)
.clamp(CAMERA_ZOOM_RANGE.start, CAMERA_ZOOM_RANGE.end)
* local_z;
}
if theta_delta != 0.0 {
camera_transform
.translate_around(Vec3::ZERO, Quat::from_axis_angle(Vec3::Y, theta_delta));
camera_transform.look_at(Vec3::ZERO, Vec3::Y);
}
}
}
// Adjusts app settings per user input.
#[allow(clippy::too_many_arguments)]
fn adjust_app_settings(
mut commands: Commands,
keyboard_input: Res<ButtonInput<KeyCode>>,
mut app_settings: ResMut<AppSettings>,
mut cameras: Query<Entity, With<Camera>>,
mut cube_models: Query<&mut Visibility, (With<CubeModel>, Without<FlightHelmetModel>)>,
mut flight_helmet_models: Query<&mut Visibility, (Without<CubeModel>, With<FlightHelmetModel>)>,
mut text: Query<&mut Text>,
) {
// If there are no changes, we're going to bail for efficiency. Record that
// here.
let mut any_changes = false;
// If the user pressed Space, toggle SSR.
if keyboard_input.just_pressed(KeyCode::Space) {
app_settings.ssr_on = !app_settings.ssr_on;
any_changes = true;
}
// If the user pressed Enter, switch models.
if keyboard_input.just_pressed(KeyCode::Enter) {
app_settings.displayed_model = match app_settings.displayed_model {
DisplayedModel::Cube => DisplayedModel::FlightHelmet,
DisplayedModel::FlightHelmet => DisplayedModel::Cube,
};
any_changes = true;
}
// If there were no changes, bail.
if !any_changes {
return;
}
// Update SSR settings.
for camera in cameras.iter_mut() {
if app_settings.ssr_on {
commands
.entity(camera)
.insert(ScreenSpaceReflections::default());
} else {
commands.entity(camera).remove::<ScreenSpaceReflections>();
}
}
// Set cube model visibility.
for mut cube_visibility in cube_models.iter_mut() {
*cube_visibility = match app_settings.displayed_model {
DisplayedModel::Cube => Visibility::Visible,
_ => Visibility::Hidden,
}
}
// Set flight helmet model visibility.
for mut flight_helmet_visibility in flight_helmet_models.iter_mut() {
*flight_helmet_visibility = match app_settings.displayed_model {
DisplayedModel::FlightHelmet => Visibility::Visible,
_ => Visibility::Hidden,
};
}
// Update the help text.
for mut text in text.iter_mut() {
*text = create_text(&app_settings);
}
}
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
fn prepare_instance_buffers(
mut commands: Commands,
query: Query<(Entity, &InstanceMaterialData)>,
render_device: Res<RenderDevice>,
) {
for (entity, instance_data) in &query {
let buffer = render_device.create_buffer_with_data(&BufferInitDescriptor {
label: Some("instance data buffer"),
contents: bytemuck::cast_slice(instance_data.as_slice()),
usage: BufferUsages::VERTEX | BufferUsages::COPY_DST,
});
commands.entity(entity).insert(InstanceBuffer {
buffer,
length: instance_data.len(),
});
}
}
- examples/asset/asset_decompression.rs
- examples/window/window_settings.rs
- examples/stress_tests/many_foxes.rs
- examples/animation/morph_targets.rs
- examples/testbed/3d.rs
- examples/games/game_menu.rs
- examples/3d/anisotropy.rs
- examples/3d/clearcoat.rs
- examples/3d/rotate_environment_map.rs
- examples/math/sampling_primitives.rs
- examples/3d/order_independent_transparency.rs
- examples/3d/pcss.rs
- examples/3d/shadow_caster_receiver.rs
- examples/3d/depth_of_field.rs
- examples/games/stepping.rs
- examples/3d/color_grading.rs
- examples/stress_tests/many_buttons.rs
- examples/3d/lightmaps.rs
- examples/3d/../helpers/widgets.rs
- examples/audio/soundtrack.rs
- examples/ui/relative_cursor_position.rs
- examples/2d/bounding_2d.rs
- examples/animation/eased_motion.rs
- examples/3d/visibility_range.rs
- examples/animation/animated_fox.rs
- examples/3d/volumetric_fog.rs
- examples/animation/animated_ui.rs
- examples/animation/animation_graph.rs
- examples/async_tasks/async_compute.rs
- examples/stress_tests/transform_hierarchy.rs
- examples/animation/animation_masks.rs
- examples/3d/deferred_rendering.rs
- examples/3d/anti_aliasing.rs
- examples/3d/ssao.rs
- examples/3d/bloom_3d.rs
- examples/2d/bloom_2d.rs
- examples/stress_tests/many_cubes.rs
- examples/animation/animated_transform.rs
- examples/3d/transmission.rs
- examples/ui/ui.rs
- examples/ui/scroll.rs
Sourcepub fn insert_if<F>(
&mut self,
bundle: impl Bundle,
condition: F,
) -> &mut EntityCommands<'a>
pub fn insert_if<F>( &mut self, bundle: impl Bundle, condition: F, ) -> &mut EntityCommands<'a>
Similar to Self::insert
but will only insert if the predicate returns true.
This is useful for chaining method calls.
§Panics
The command will panic when applied if the associated entity does not exist.
To avoid a panic in this case, use the command Self::try_insert_if
instead.
§Example
#[derive(Component)]
struct StillLoadingStats;
#[derive(Component)]
struct Health(u32);
fn add_health_system(mut commands: Commands, player: Res<PlayerEntity>) {
commands
.entity(player.entity)
.insert_if(Health(10), || !player.is_spectator())
.remove::<StillLoadingStats>();
}
Examples found in repository?
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
fn spawn_cars(
asset_server: &AssetServer,
meshes: &mut Assets<Mesh>,
materials: &mut Assets<StandardMaterial>,
commands: &mut Commands,
) {
const N_CARS: usize = 20;
let box_mesh = meshes.add(Cuboid::new(0.3, 0.15, 0.55));
let cylinder = meshes.add(Cylinder::default());
let logo = asset_server.load("branding/icon.png");
let wheel_matl = materials.add(StandardMaterial {
base_color: Color::WHITE,
base_color_texture: Some(logo.clone()),
..default()
});
let mut matl = |color| {
materials.add(StandardMaterial {
base_color: color,
..default()
})
};
let colors = [
matl(Color::linear_rgb(1.0, 0.0, 0.0)),
matl(Color::linear_rgb(1.0, 1.0, 0.0)),
matl(Color::BLACK),
matl(Color::linear_rgb(0.0, 0.0, 1.0)),
matl(Color::linear_rgb(0.0, 1.0, 0.0)),
matl(Color::linear_rgb(1.0, 0.0, 1.0)),
matl(Color::linear_rgb(0.5, 0.5, 0.0)),
matl(Color::linear_rgb(1.0, 0.5, 0.0)),
];
for i in 0..N_CARS {
let color = colors[i % colors.len()].clone();
commands
.spawn((
Mesh3d(box_mesh.clone()),
MeshMaterial3d(color.clone()),
Transform::from_scale(Vec3::splat(0.5)),
Moves(i as f32 * 2.0),
))
.insert_if(CameraTracked, || i == 0)
.with_children(|parent| {
parent.spawn((
Mesh3d(box_mesh.clone()),
MeshMaterial3d(color),
Transform::from_xyz(0.0, 0.08, 0.03).with_scale(Vec3::new(1.0, 1.0, 0.5)),
));
let mut spawn_wheel = |x: f32, z: f32| {
parent.spawn((
Mesh3d(cylinder.clone()),
MeshMaterial3d(wheel_matl.clone()),
Transform::from_xyz(0.14 * x, -0.045, 0.15 * z)
.with_scale(Vec3::new(0.15, 0.04, 0.15))
.with_rotation(Quat::from_rotation_z(std::f32::consts::FRAC_PI_2)),
Rotates,
));
};
spawn_wheel(1.0, 1.0);
spawn_wheel(1.0, -1.0);
spawn_wheel(-1.0, 1.0);
spawn_wheel(-1.0, -1.0);
});
}
}
More examples
92 93 94 95 96 97 98 99 100 101 102 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 195 196 197 198
fn update(
camera: Single<
(
Entity,
Option<&ScreenSpaceAmbientOcclusion>,
Option<&TemporalJitter>,
),
With<Camera>,
>,
mut text: Single<&mut Text>,
mut sphere: Single<&mut Transform, With<SphereMarker>>,
mut commands: Commands,
keycode: Res<ButtonInput<KeyCode>>,
time: Res<Time>,
) {
sphere.translation.y = ops::sin(time.elapsed_secs() / 1.7) * 0.7;
let (camera_entity, ssao, temporal_jitter) = *camera;
let current_ssao = ssao.cloned().unwrap_or_default();
let mut commands = commands.entity(camera_entity);
commands
.insert_if(
ScreenSpaceAmbientOcclusion {
quality_level: ScreenSpaceAmbientOcclusionQualityLevel::Low,
..current_ssao
},
|| keycode.just_pressed(KeyCode::Digit2),
)
.insert_if(
ScreenSpaceAmbientOcclusion {
quality_level: ScreenSpaceAmbientOcclusionQualityLevel::Medium,
..current_ssao
},
|| keycode.just_pressed(KeyCode::Digit3),
)
.insert_if(
ScreenSpaceAmbientOcclusion {
quality_level: ScreenSpaceAmbientOcclusionQualityLevel::High,
..current_ssao
},
|| keycode.just_pressed(KeyCode::Digit4),
)
.insert_if(
ScreenSpaceAmbientOcclusion {
quality_level: ScreenSpaceAmbientOcclusionQualityLevel::Ultra,
..current_ssao
},
|| keycode.just_pressed(KeyCode::Digit5),
)
.insert_if(
ScreenSpaceAmbientOcclusion {
constant_object_thickness: (current_ssao.constant_object_thickness * 2.0).min(4.0),
..current_ssao
},
|| keycode.just_pressed(KeyCode::ArrowUp),
)
.insert_if(
ScreenSpaceAmbientOcclusion {
constant_object_thickness: (current_ssao.constant_object_thickness * 0.5)
.max(0.0625),
..current_ssao
},
|| keycode.just_pressed(KeyCode::ArrowDown),
);
if keycode.just_pressed(KeyCode::Digit1) {
commands.remove::<ScreenSpaceAmbientOcclusion>();
}
if keycode.just_pressed(KeyCode::Space) {
if temporal_jitter.is_some() {
commands.remove::<TemporalJitter>();
} else {
commands.insert(TemporalJitter::default());
}
}
text.clear();
let (o, l, m, h, u) = match ssao.map(|s| s.quality_level) {
None => ("*", "", "", "", ""),
Some(ScreenSpaceAmbientOcclusionQualityLevel::Low) => ("", "*", "", "", ""),
Some(ScreenSpaceAmbientOcclusionQualityLevel::Medium) => ("", "", "*", "", ""),
Some(ScreenSpaceAmbientOcclusionQualityLevel::High) => ("", "", "", "*", ""),
Some(ScreenSpaceAmbientOcclusionQualityLevel::Ultra) => ("", "", "", "", "*"),
_ => unreachable!(),
};
if let Some(thickness) = ssao.map(|s| s.constant_object_thickness) {
text.push_str(&format!(
"Constant object thickness: {} (Up/Down)\n\n",
thickness
));
}
text.push_str("SSAO Quality:\n");
text.push_str(&format!("(1) {o}Off{o}\n"));
text.push_str(&format!("(2) {l}Low{l}\n"));
text.push_str(&format!("(3) {m}Medium{m}\n"));
text.push_str(&format!("(4) {h}High{h}\n"));
text.push_str(&format!("(5) {u}Ultra{u}\n\n"));
text.push_str("Temporal Antialiasing:\n");
text.push_str(match temporal_jitter {
Some(_) => "(Space) Enabled",
None => "(Space) Disabled",
});
}
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 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
fn setup(
mut commands: Commands,
args: Res<Args>,
mesh_assets: 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_assets = mesh_assets.into_inner();
let meshes = init_meshes(args, mesh_assets);
let material_textures = init_textures(args, images);
let materials = init_materials(args, &material_textures, material_assets);
// We're seeding the PRNG here to make this example deterministic for testing purposes.
// This isn't strictly required in practical use unless you need your app to be deterministic.
let mut material_rng = ChaCha8Rng::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);
let (mesh, transform) = meshes.choose(&mut material_rng).unwrap();
commands
.spawn((
Mesh3d(mesh.clone()),
MeshMaterial3d(materials.choose(&mut material_rng).unwrap().clone()),
Transform::from_translation((radius * unit_sphere_p).as_vec3())
.looking_at(Vec3::ZERO, Vec3::Y)
.mul_transform(*transform),
))
.insert_if(NoFrustumCulling, || args.no_frustum_culling)
.insert_if(NoAutomaticBatching, || args.no_automatic_batching);
}
// camera
let mut camera = commands.spawn(Camera3d::default());
if args.gpu_culling {
camera.insert(GpuCulling);
}
if args.no_cpu_culling {
camera.insert(NoCpuCulling);
}
// Inside-out box around the meshes onto which shadows are cast (though you cannot see them...)
commands.spawn((
Mesh3d(mesh_assets.add(Cuboid::from_size(Vec3::splat(radius as f32 * 2.2)))),
MeshMaterial3d(material_assets.add(StandardMaterial::from(Color::WHITE))),
Transform::from_scale(-Vec3::ONE),
NotShadowCaster,
));
}
_ => {
// 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.
let scale = 2.5;
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((
Mesh3d(meshes.choose(&mut material_rng).unwrap().0.clone()),
MeshMaterial3d(materials.choose(&mut material_rng).unwrap().clone()),
Transform::from_xyz((x as f32) * scale, (y as f32) * scale, 0.0),
));
commands.spawn((
Mesh3d(meshes.choose(&mut material_rng).unwrap().0.clone()),
MeshMaterial3d(materials.choose(&mut material_rng).unwrap().clone()),
Transform::from_xyz(
(x as f32) * scale,
HEIGHT as f32 * scale,
(y as f32) * scale,
),
));
commands.spawn((
Mesh3d(meshes.choose(&mut material_rng).unwrap().0.clone()),
MeshMaterial3d(materials.choose(&mut material_rng).unwrap().clone()),
Transform::from_xyz((x as f32) * scale, 0.0, (y as f32) * scale),
));
commands.spawn((
Mesh3d(meshes.choose(&mut material_rng).unwrap().0.clone()),
MeshMaterial3d(materials.choose(&mut material_rng).unwrap().clone()),
Transform::from_xyz(0.0, (x as f32) * scale, (y as f32) * scale),
));
}
}
// camera
let center = 0.5 * scale * Vec3::new(WIDTH as f32, HEIGHT as f32, WIDTH as f32);
commands.spawn((Camera3d::default(), Transform::from_translation(center)));
// Inside-out box around the meshes onto which shadows are cast (though you cannot see them...)
commands.spawn((
Mesh3d(mesh_assets.add(Cuboid::from_size(2.0 * 1.1 * center))),
MeshMaterial3d(material_assets.add(StandardMaterial::from(Color::WHITE))),
Transform::from_scale(-Vec3::ONE).with_translation(center),
NotShadowCaster,
));
}
}
commands.spawn((
DirectionalLight {
shadows_enabled: args.shadows,
..default()
},
Transform::IDENTITY.looking_at(Vec3::new(0.0, -1.0, -1.0), Vec3::Y),
));
}
Sourcepub fn insert_if_new(&mut self, bundle: impl Bundle) -> &mut EntityCommands<'a>
pub fn insert_if_new(&mut self, bundle: impl Bundle) -> &mut EntityCommands<'a>
Adds a Bundle
of components to the entity without overwriting.
This is the same as EntityCommands::insert
, but in case of duplicate
components will leave the old values instead of replacing them with new
ones.
See also entry
, which lets you modify a Component
if it’s present,
as well as initialize it with a default value.
§Panics
The command will panic when applied if the associated entity does not exist.
To avoid a panic in this case, use the command Self::try_insert_if_new
instead.
Sourcepub fn insert_if_new_and<F>(
&mut self,
bundle: impl Bundle,
condition: F,
) -> &mut EntityCommands<'a>
pub fn insert_if_new_and<F>( &mut self, bundle: impl Bundle, condition: F, ) -> &mut EntityCommands<'a>
Adds a Bundle
of components to the entity without overwriting if the
predicate returns true.
This is the same as EntityCommands::insert_if
, but in case of duplicate
components will leave the old values instead of replacing them with new
ones.
§Panics
The command will panic when applied if the associated entity does not exist.
To avoid a panic in this case, use the command Self::try_insert_if_new
instead.
Sourcepub unsafe fn insert_by_id<T>(
&mut self,
component_id: ComponentId,
value: T,
) -> &mut EntityCommands<'a>where
T: Send + 'static,
pub unsafe fn insert_by_id<T>(
&mut self,
component_id: ComponentId,
value: T,
) -> &mut EntityCommands<'a>where
T: Send + 'static,
Adds a dynamic component to an entity.
See EntityWorldMut::insert_by_id
for more information.
§Panics
The command will panic when applied if the associated entity does not exist.
To avoid a panic in this case, use the command Self::try_insert_by_id
instead.
§Safety
ComponentId
must be from the same world asself
.T
must have the same layout as the one passed duringcomponent_id
creation.
Sourcepub unsafe fn try_insert_by_id<T>(
&mut self,
component_id: ComponentId,
value: T,
) -> &mut EntityCommands<'a>where
T: Send + 'static,
pub unsafe fn try_insert_by_id<T>(
&mut self,
component_id: ComponentId,
value: T,
) -> &mut EntityCommands<'a>where
T: Send + 'static,
Attempts to add a dynamic component to an entity.
See EntityWorldMut::insert_by_id
for more information.
§Safety
ComponentId
must be from the same world asself
.T
must have the same layout as the one passed duringcomponent_id
creation.
Sourcepub fn try_insert(&mut self, bundle: impl Bundle) -> &mut EntityCommands<'a>
pub fn try_insert(&mut self, bundle: impl Bundle) -> &mut EntityCommands<'a>
Tries to add a Bundle
of components to the entity.
This will overwrite any previous value(s) of the same component type.
§Note
Unlike Self::insert
, this will not panic if the associated entity does not exist.
§Example
#[derive(Component)]
struct Health(u32);
#[derive(Component)]
struct Strength(u32);
#[derive(Component)]
struct Defense(u32);
#[derive(Bundle)]
struct CombatBundle {
health: Health,
strength: Strength,
}
fn add_combat_stats_system(mut commands: Commands, player: Res<PlayerEntity>) {
commands.entity(player.entity)
// You can try_insert individual components:
.try_insert(Defense(10))
// You can also insert tuples of components:
.try_insert(CombatBundle {
health: Health(100),
strength: Strength(40),
});
// Suppose this occurs in a parallel adjacent system or process
commands.entity(player.entity)
.despawn();
commands.entity(player.entity)
// This will not panic nor will it add the component
.try_insert(Defense(5));
}
Sourcepub fn try_insert_if<F>(
&mut self,
bundle: impl Bundle,
condition: F,
) -> &mut EntityCommands<'a>
pub fn try_insert_if<F>( &mut self, bundle: impl Bundle, condition: F, ) -> &mut EntityCommands<'a>
Similar to Self::try_insert
but will only try to insert if the predicate returns true.
This is useful for chaining method calls.
§Example
#[derive(Component)]
struct StillLoadingStats;
#[derive(Component)]
struct Health(u32);
fn add_health_system(mut commands: Commands, player: Res<PlayerEntity>) {
commands.entity(player.entity)
.try_insert_if(Health(10), || !player.is_spectator())
.remove::<StillLoadingStats>();
commands.entity(player.entity)
// This will not panic nor will it add the component
.try_insert_if(Health(5), || !player.is_spectator());
}
Sourcepub fn try_insert_if_new_and<F>(
&mut self,
bundle: impl Bundle,
condition: F,
) -> &mut EntityCommands<'a>
pub fn try_insert_if_new_and<F>( &mut self, bundle: impl Bundle, condition: F, ) -> &mut EntityCommands<'a>
Tries to add a Bundle
of components to the entity without overwriting if the
predicate returns true.
This is the same as EntityCommands::try_insert_if
, but in case of duplicate
components will leave the old values instead of replacing them with new
ones.
§Note
Unlike Self::insert_if_new_and
, this will not panic if the associated entity does
not exist.
§Example
#[derive(Component)]
struct StillLoadingStats;
#[derive(Component)]
struct Health(u32);
fn add_health_system(mut commands: Commands, player: Res<PlayerEntity>) {
commands.entity(player.entity)
.try_insert_if(Health(10), || player.is_spectator())
.remove::<StillLoadingStats>();
commands.entity(player.entity)
// This will not panic nor will it overwrite the component
.try_insert_if_new_and(Health(5), || player.is_spectator());
}
Sourcepub fn try_insert_if_new(
&mut self,
bundle: impl Bundle,
) -> &mut EntityCommands<'a>
pub fn try_insert_if_new( &mut self, bundle: impl Bundle, ) -> &mut EntityCommands<'a>
Tries to add a Bundle
of components to the entity without overwriting.
This is the same as EntityCommands::try_insert
, but in case of duplicate
components will leave the old values instead of replacing them with new
ones.
§Note
Unlike Self::insert_if_new
, this will not panic if the associated entity does not exist.
Sourcepub fn remove<T>(&mut self) -> &mut EntityCommands<'a>where
T: Bundle,
pub fn remove<T>(&mut self) -> &mut EntityCommands<'a>where
T: Bundle,
Removes a Bundle
of components from the entity.
§Example
#[derive(Component)]
struct Health(u32);
#[derive(Component)]
struct Strength(u32);
#[derive(Component)]
struct Defense(u32);
#[derive(Bundle)]
struct CombatBundle {
health: Health,
strength: Strength,
}
fn remove_combat_stats_system(mut commands: Commands, player: Res<PlayerEntity>) {
commands
.entity(player.entity)
// You can remove individual components:
.remove::<Defense>()
// You can also remove pre-defined Bundles of components:
.remove::<CombatBundle>()
// You can also remove tuples of components and bundles.
// This is equivalent to the calls above:
.remove::<(Defense, CombatBundle)>();
}
Examples found in repository?
More examples
38 39 40 41 42 43 44 45 46 47 48 49
fn remove_component(
time: Res<Time>,
mut commands: Commands,
query: Query<Entity, With<MyComponent>>,
) {
// After two seconds have passed the `Component` is removed.
if time.elapsed_secs() > 2.0 {
if let Some(entity) = query.iter().next() {
commands.entity(entity).remove::<MyComponent>();
}
}
}
104 105 106 107 108 109 110 111 112 113 114 115 116 117
fn trigger_hooks(
mut commands: Commands,
keys: Res<ButtonInput<KeyCode>>,
index: Res<MyComponentIndex>,
) {
for (key, entity) in index.iter() {
if !keys.pressed(*key) {
commands.entity(*entity).remove::<MyComponent>();
}
}
for key in keys.get_just_pressed() {
commands.spawn(MyComponent(*key));
}
}
111 112 113 114 115 116 117 118 119 120 121 122 123
fn fade_in(
mut commands: Commands,
mut audio_sink: Query<(&mut AudioSink, Entity), With<FadeIn>>,
time: Res<Time>,
) {
for (audio, entity) in audio_sink.iter_mut() {
audio.set_volume(audio.volume() + time.delta_secs() / FADE_TIME);
if audio.volume() >= 1.0 {
audio.set_volume(1.0);
commands.entity(entity).remove::<FadeIn>();
}
}
}
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
fn update_dof_settings(
mut commands: Commands,
view_targets: Query<Entity, With<Camera>>,
app_settings: Res<AppSettings>,
) {
let depth_of_field: Option<DepthOfField> = (*app_settings).into();
for view in view_targets.iter() {
match depth_of_field {
None => {
commands.entity(view).remove::<DepthOfField>();
}
Some(depth_of_field) => {
commands.entity(view).insert(depth_of_field);
}
}
}
}
- examples/window/screenshot.rs
- examples/asset/asset_decompression.rs
- examples/games/game_menu.rs
- examples/3d/clearcoat.rs
- examples/math/sampling_primitives.rs
- examples/3d/order_independent_transparency.rs
- examples/3d/irradiance_volumes.rs
- examples/3d/shadow_caster_receiver.rs
- examples/3d/pcss.rs
- examples/3d/reflection_probes.rs
- examples/3d/volumetric_fog.rs
- examples/3d/ssr.rs
- examples/3d/anisotropy.rs
- examples/animation/animation_masks.rs
- examples/3d/deferred_rendering.rs
- examples/3d/anti_aliasing.rs
- examples/3d/ssao.rs
- examples/3d/bloom_3d.rs
- examples/2d/bloom_2d.rs
- examples/3d/transmission.rs
Sourcepub fn remove_with_requires<T>(&mut self) -> &mut EntityCommands<'a>where
T: Bundle,
pub fn remove_with_requires<T>(&mut self) -> &mut EntityCommands<'a>where
T: Bundle,
Removes all components in the Bundle
components and remove all required components for each component in the Bundle
from entity.
§Example
use bevy_ecs::prelude::*;
#[derive(Component)]
#[require(B)]
struct A;
#[derive(Component, Default)]
struct B;
#[derive(Resource)]
struct PlayerEntity { entity: Entity }
fn remove_with_requires_system(mut commands: Commands, player: Res<PlayerEntity>) {
commands
.entity(player.entity)
// Remove both A and B components from the entity, because B is required by A
.remove_with_requires::<A>();
}
Sourcepub fn remove_by_id(
&mut self,
component_id: ComponentId,
) -> &mut EntityCommands<'a>
pub fn remove_by_id( &mut self, component_id: ComponentId, ) -> &mut EntityCommands<'a>
Removes a component from the entity.
Sourcepub fn clear(&mut self) -> &mut EntityCommands<'a>
pub fn clear(&mut self) -> &mut EntityCommands<'a>
Removes all components associated with the entity.
Sourcepub fn despawn(&mut self)
pub fn despawn(&mut self)
Despawns the entity. This will emit a warning if the entity does not exist.
See World::despawn
for more details.
§Note
This won’t clean up external references to the entity (such as parent-child relationships
if you’re using bevy_hierarchy
), which may leave the world in an invalid state.
§Example
fn remove_character_system(
mut commands: Commands,
character_to_remove: Res<CharacterToRemove>
)
{
commands.entity(character_to_remove.entity).despawn();
}
Examples found in repository?
More examples
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
fn close_on_esc(
mut commands: Commands,
focused_windows: Query<(Entity, &Window)>,
input: Res<ButtonInput<KeyCode>>,
) {
for (window, focus) in focused_windows.iter() {
if !focus.focused {
continue;
}
if input.just_pressed(KeyCode::Escape) {
commands.entity(window).despawn();
}
}
}
66 67 68 69 70 71 72 73 74 75 76 77
fn move_text(
mut commands: Commands,
mut texts: Query<(Entity, &mut Transform), With<Text2d>>,
time: Res<Time>,
) {
for (entity, mut position) in &mut texts {
position.translation -= Vec3::new(0.0, 100.0 * time.delta_secs(), 0.0);
if position.translation.y < -300.0 {
commands.entity(entity).despawn();
}
}
}
94 95 96 97 98 99 100 101 102 103 104 105
fn bubbling_text(
mut commands: Commands,
mut bubbles: Query<(Entity, &mut Transform, &mut Bubble)>,
time: Res<Time>,
) {
for (entity, mut transform, mut bubble) in bubbles.iter_mut() {
if bubble.timer.tick(time.delta()).just_finished() {
commands.entity(entity).despawn();
}
transform.translation.y += time.delta_secs() * 100.0;
}
}
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
fn explode_mine(trigger: Trigger<Explode>, query: Query<&Mine>, mut commands: Commands) {
// If a triggered event is targeting a specific entity you can access it with `.entity()`
let id = trigger.entity();
let Some(mut entity) = commands.get_entity(id) else {
return;
};
info!("Boom! {:?} exploded.", id.index());
entity.despawn();
let mine = query.get(id).unwrap();
// Trigger another explosion cascade.
commands.trigger(ExplodeMines {
pos: mine.pos,
radius: mine.size,
});
}
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
fn environment_map_load_finish(
mut commands: Commands,
asset_server: Res<AssetServer>,
environment_maps: Query<&EnvironmentMapLight>,
label_query: Query<Entity, With<EnvironmentMapLabel>>,
) {
if let Ok(environment_map) = environment_maps.get_single() {
if asset_server
.load_state(&environment_map.diffuse_map)
.is_loaded()
&& asset_server
.load_state(&environment_map.specular_map)
.is_loaded()
{
if let Ok(label_entity) = label_query.get_single() {
commands.entity(label_entity).despawn();
}
}
}
}
Sourcepub fn try_despawn(&mut self)
pub fn try_despawn(&mut self)
Despawns the entity.
This will not emit a warning if the entity does not exist, essentially performing
the same function as Self::despawn
without emitting warnings.
Sourcepub fn queue<M>(
&mut self,
command: impl EntityCommand<M>,
) -> &mut EntityCommands<'a>where
M: 'static,
pub fn queue<M>(
&mut self,
command: impl EntityCommand<M>,
) -> &mut EntityCommands<'a>where
M: 'static,
Pushes an EntityCommand
to the queue, which will get executed for the current Entity
.
§Examples
commands
.spawn_empty()
// Closures with this signature implement `EntityCommand`.
.queue(|entity: EntityWorldMut| {
println!("Executed an EntityCommand for {:?}", entity.id());
});
Sourcepub fn retain<T>(&mut self) -> &mut EntityCommands<'a>where
T: Bundle,
pub fn retain<T>(&mut self) -> &mut EntityCommands<'a>where
T: Bundle,
Removes all components except the given Bundle
from the entity.
This can also be used to remove all the components from the entity by passing it an empty Bundle.
§Example
#[derive(Component)]
struct Health(u32);
#[derive(Component)]
struct Strength(u32);
#[derive(Component)]
struct Defense(u32);
#[derive(Bundle)]
struct CombatBundle {
health: Health,
strength: Strength,
}
fn remove_combat_stats_system(mut commands: Commands, player: Res<PlayerEntity>) {
commands
.entity(player.entity)
// You can retain a pre-defined Bundle of components,
// with this removing only the Defense component
.retain::<CombatBundle>()
// You can also retain only a single component
.retain::<Health>()
// And you can remove all the components by passing in an empty Bundle
.retain::<()>();
}
Sourcepub fn log_components(&mut self) -> &mut EntityCommands<'a>
pub fn log_components(&mut self) -> &mut EntityCommands<'a>
Logs the components of the entity at the info level.
§Panics
The command will panic when applied if the associated entity does not exist.
Sourcepub fn commands_mut(&mut self) -> &mut Commands<'a, 'a>
pub fn commands_mut(&mut self) -> &mut Commands<'a, 'a>
Returns a mutable reference to the underlying Commands
.
Sourcepub fn trigger(&mut self, event: impl Event) -> &mut EntityCommands<'a>
pub fn trigger(&mut self, event: impl Event) -> &mut EntityCommands<'a>
Sourcepub fn observe<E, B, M>(
&mut self,
system: impl IntoObserverSystem<E, B, M>,
) -> &mut EntityCommands<'a>
pub fn observe<E, B, M>( &mut self, system: impl IntoObserverSystem<E, B, M>, ) -> &mut EntityCommands<'a>
Creates an Observer
listening for a trigger of type T
that targets this entity.
Examples found in repository?
18 19 20 21 22 23 24 25 26 27 28 29 30
fn screenshot_on_spacebar(
mut commands: Commands,
input: Res<ButtonInput<KeyCode>>,
mut counter: Local<u32>,
) {
if input.just_pressed(KeyCode::Space) {
let path = format!("./screenshot-{}.png", *counter);
*counter += 1;
commands
.spawn(Screenshot::primary_window())
.observe(save_to_disk(path));
}
}
More examples
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
fn setup(mut commands: Commands) {
commands
.spawn((Name::new("Goblin"), HitPoints(50)))
.observe(take_damage)
.with_children(|parent| {
parent
.spawn((Name::new("Helmet"), Armor(5)))
.observe(block_attack);
parent
.spawn((Name::new("Socks"), Armor(10)))
.observe(block_attack);
parent
.spawn((Name::new("Shirt"), Armor(15)))
.observe(block_attack);
});
}
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
pub fn setup(
mut commands: Commands,
asset_server: Res<AssetServer>,
mut graphs: ResMut<Assets<AnimationGraph>>,
) {
let (graph, node) = AnimationGraph::from_clip(
asset_server.load(GltfAssetLabel::Animation(2).from_asset(FOX_PATH)),
);
let graph_handle = graphs.add(graph);
commands.insert_resource(Animation {
animation: node,
graph: graph_handle,
});
commands.spawn((
Camera3d::default(),
Transform::from_xyz(100.0, 100.0, 150.0).looking_at(Vec3::new(0.0, 20.0, 0.0), Vec3::Y),
StateScoped(CURRENT_SCENE),
));
commands.spawn((
Transform::from_rotation(Quat::from_euler(EulerRot::ZYX, 0.0, 1.0, -PI / 4.)),
DirectionalLight {
shadows_enabled: true,
..default()
},
StateScoped(CURRENT_SCENE),
));
commands
.spawn((
SceneRoot(asset_server.load(GltfAssetLabel::Scene(0).from_asset(FOX_PATH))),
StateScoped(CURRENT_SCENE),
))
.observe(pause_animation_frame);
}
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 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
fn setup_scene(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
) {
commands
.spawn((
Text::new("Click Me to get a box\nDrag cubes to rotate"),
Node {
position_type: PositionType::Absolute,
top: Val::Percent(12.0),
left: Val::Percent(12.0),
..default()
},
))
.observe(on_click_spawn_cube)
.observe(
|out: Trigger<Pointer<Out>>, mut texts: Query<&mut TextColor>| {
let mut text_color = texts.get_mut(out.entity()).unwrap();
text_color.0 = Color::WHITE;
},
)
.observe(
|over: Trigger<Pointer<Over>>, mut texts: Query<&mut TextColor>| {
let mut color = texts.get_mut(over.entity()).unwrap();
color.0 = bevy::color::palettes::tailwind::CYAN_400.into();
},
);
// Base
commands.spawn((
Mesh3d(meshes.add(Circle::new(4.0))),
MeshMaterial3d(materials.add(Color::WHITE)),
Transform::from_rotation(Quat::from_rotation_x(-std::f32::consts::FRAC_PI_2)),
));
// Light
commands.spawn((
PointLight {
shadows_enabled: true,
..default()
},
Transform::from_xyz(4.0, 8.0, 4.0),
));
// Camera
commands.spawn((
Camera3d::default(),
Transform::from_xyz(-2.5, 4.5, 9.0).looking_at(Vec3::ZERO, Vec3::Y),
));
}
fn on_click_spawn_cube(
_click: Trigger<Pointer<Click>>,
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
mut num: Local<usize>,
) {
commands
.spawn((
Mesh3d(meshes.add(Cuboid::new(0.5, 0.5, 0.5))),
MeshMaterial3d(materials.add(Color::srgb_u8(124, 144, 255))),
Transform::from_xyz(0.0, 0.25 + 0.55 * *num as f32, 0.0),
))
// With the MeshPickingPlugin added, you can add pointer event observers to meshes:
.observe(on_drag_rotate);
*num += 1;
}
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
fn setup(mut commands: Commands) {
commands.spawn(Camera2d);
commands.spawn((
Text::new(
"Click on a \"Mine\" to trigger it.\n\
When it explodes it will trigger all overlapping mines.",
),
Node {
position_type: PositionType::Absolute,
top: Val::Px(12.),
left: Val::Px(12.),
..default()
},
));
let mut rng = ChaCha8Rng::seed_from_u64(19878367467713);
commands
.spawn(Mine::random(&mut rng))
// Observers can watch for events targeting a specific entity.
// This will create a new observer that runs whenever the Explode event
// is triggered for this spawned entity.
.observe(explode_mine);
// We want to spawn a bunch of mines. We could just call the code above for each of them.
// That would create a new observer instance for every Mine entity. Having duplicate observers
// generally isn't worth worrying about as the overhead is low. But if you want to be maximally efficient,
// you can reuse observers across entities.
//
// First, observers are actually just entities with the Observer component! The `observe()` functions
// you've seen so far in this example are just shorthand for manually spawning an observer.
let mut observer = Observer::new(explode_mine);
// As we spawn entities, we can make this observer watch each of them:
for _ in 0..1000 {
let entity = commands.spawn(Mine::random(&mut rng)).id();
observer.watch_entity(entity);
}
// By spawning the Observer component, it becomes active!
commands.spawn(observer);
}
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 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
fn setup(
mut commands: Commands,
mut images: ResMut<Assets<Image>>,
mut buffers: ResMut<Assets<ShaderStorageBuffer>>,
) {
// Create a storage buffer with some data
let buffer = vec![0u32; BUFFER_LEN];
let mut buffer = ShaderStorageBuffer::from(buffer);
// We need to enable the COPY_SRC usage so we can copy the buffer to the cpu
buffer.buffer_description.usage |= BufferUsages::COPY_SRC;
let buffer = buffers.add(buffer);
// Create a storage texture with some data
let size = Extent3d {
width: BUFFER_LEN as u32,
height: 1,
..default()
};
let mut image = Image::new_fill(
size,
TextureDimension::D2,
&[0, 0, 0, 0],
TextureFormat::R32Uint,
RenderAssetUsages::RENDER_WORLD,
);
// We also need to enable the COPY_SRC, as well as STORAGE_BINDING so we can use it in the
// compute shader
image.texture_descriptor.usage |= TextureUsages::COPY_SRC | TextureUsages::STORAGE_BINDING;
let image = images.add(image);
// Spawn the readback components. For each frame, the data will be read back from the GPU
// asynchronously and trigger the `ReadbackComplete` event on this entity. Despawn the entity
// to stop reading back the data.
commands.spawn(Readback::buffer(buffer.clone())).observe(
|trigger: Trigger<ReadbackComplete>| {
// This matches the type which was used to create the `ShaderStorageBuffer` above,
// and is a convenient way to interpret the data.
let data: Vec<u32> = trigger.event().to_shader_type();
info!("Buffer {:?}", data);
},
);
// This is just a simple way to pass the buffer handle to the render app for our compute node
commands.insert_resource(ReadbackBuffer(buffer));
// Textures can also be read back from the GPU. Pay careful attention to the format of the
// texture, as it will affect how the data is interpreted.
commands.spawn(Readback::texture(image.clone())).observe(
|trigger: Trigger<ReadbackComplete>| {
// You probably want to interpret the data as a color rather than a `ShaderType`,
// but in this case we know the data is a single channel storage texture, so we can
// interpret it as a `Vec<u32>`
let data: Vec<u32> = trigger.event().to_shader_type();
info!("Image {:?}", data);
},
);
commands.insert_resource(ReadbackImage(image));
}
Trait Implementations§
Source§impl BuildChildren for EntityCommands<'_>
impl BuildChildren for EntityCommands<'_>
Source§type Builder<'a> = ChildBuilder<'a>
type Builder<'a> = ChildBuilder<'a>
Source§fn with_children(
&mut self,
spawn_children: impl FnOnce(&mut <EntityCommands<'_> as BuildChildren>::Builder<'_>),
) -> &mut EntityCommands<'_>
fn with_children( &mut self, spawn_children: impl FnOnce(&mut <EntityCommands<'_> as BuildChildren>::Builder<'_>), ) -> &mut EntityCommands<'_>
ChildBuild
. Read moreSource§fn with_child<B>(&mut self, bundle: B) -> &mut EntityCommands<'_>where
B: Bundle,
fn with_child<B>(&mut self, bundle: B) -> &mut EntityCommands<'_>where
B: Bundle,
Source§fn add_children(&mut self, children: &[Entity]) -> &mut EntityCommands<'_>
fn add_children(&mut self, children: &[Entity]) -> &mut EntityCommands<'_>
Source§fn insert_children(
&mut self,
index: usize,
children: &[Entity],
) -> &mut EntityCommands<'_>
fn insert_children( &mut self, index: usize, children: &[Entity], ) -> &mut EntityCommands<'_>
Source§fn remove_children(&mut self, children: &[Entity]) -> &mut EntityCommands<'_>
fn remove_children(&mut self, children: &[Entity]) -> &mut EntityCommands<'_>
Source§fn add_child(&mut self, child: Entity) -> &mut EntityCommands<'_>
fn add_child(&mut self, child: Entity) -> &mut EntityCommands<'_>
Source§fn clear_children(&mut self) -> &mut EntityCommands<'_>
fn clear_children(&mut self) -> &mut EntityCommands<'_>
Children
component will be removed if it exists, otherwise this does nothing.Source§fn replace_children(&mut self, children: &[Entity]) -> &mut EntityCommands<'_>
fn replace_children(&mut self, children: &[Entity]) -> &mut EntityCommands<'_>
Source§fn set_parent(&mut self, parent: Entity) -> &mut EntityCommands<'_>
fn set_parent(&mut self, parent: Entity) -> &mut EntityCommands<'_>
Source§fn remove_parent(&mut self) -> &mut EntityCommands<'_>
fn remove_parent(&mut self) -> &mut EntityCommands<'_>
Source§impl BuildChildrenTransformExt for EntityCommands<'_>
impl BuildChildrenTransformExt for EntityCommands<'_>
Source§fn set_parent_in_place(&mut self, parent: Entity) -> &mut EntityCommands<'_>
fn set_parent_in_place(&mut self, parent: Entity) -> &mut EntityCommands<'_>
GlobalTransform
by updating its Transform
. Read moreSource§fn remove_parent_in_place(&mut self) -> &mut EntityCommands<'_>
fn remove_parent_in_place(&mut self) -> &mut EntityCommands<'_>
GlobalTransform
by updating its Transform
to be equal to its current GlobalTransform
. Read moreSource§impl DespawnRecursiveExt for EntityCommands<'_>
impl DespawnRecursiveExt for EntityCommands<'_>
Source§fn despawn_recursive(self)
fn despawn_recursive(self)
Despawns the provided entity and its children. This will emit warnings for any entity that does not exist.
Source§fn try_despawn_recursive(self)
fn try_despawn_recursive(self)
Despawns the provided entity and its children. This will never emit warnings.
Source§fn despawn_descendants(&mut self) -> &mut EntityCommands<'_>
fn despawn_descendants(&mut self) -> &mut EntityCommands<'_>
Source§fn try_despawn_descendants(&mut self) -> &mut EntityCommands<'_>
fn try_despawn_descendants(&mut self) -> &mut EntityCommands<'_>
Self::despawn_descendants
but does not emit warningsSource§impl ReflectCommandExt for EntityCommands<'_>
impl ReflectCommandExt for EntityCommands<'_>
Source§fn insert_reflect(
&mut self,
component: Box<dyn PartialReflect>,
) -> &mut EntityCommands<'_>
fn insert_reflect( &mut self, component: Box<dyn PartialReflect>, ) -> &mut EntityCommands<'_>
AppTypeRegistry
. Read moreSource§fn insert_reflect_with_registry<T>(
&mut self,
component: Box<dyn PartialReflect>,
) -> &mut EntityCommands<'_>
fn insert_reflect_with_registry<T>( &mut self, component: Box<dyn PartialReflect>, ) -> &mut EntityCommands<'_>
insert_reflect
, but using the T
resource as type registry instead of
AppTypeRegistry
. Read moreSource§fn remove_reflect(
&mut self,
component_type_path: impl Into<Cow<'static, str>>,
) -> &mut EntityCommands<'_>
fn remove_reflect( &mut self, component_type_path: impl Into<Cow<'static, str>>, ) -> &mut EntityCommands<'_>
AppTypeRegistry
. Read moreSource§fn remove_reflect_with_registry<T>(
&mut self,
component_type_name: impl Into<Cow<'static, str>>,
) -> &mut EntityCommands<'_>
fn remove_reflect_with_registry<T>( &mut self, component_type_name: impl Into<Cow<'static, str>>, ) -> &mut EntityCommands<'_>
Auto Trait Implementations§
impl<'a> Freeze for EntityCommands<'a>
impl<'a> RefUnwindSafe for EntityCommands<'a>
impl<'a> Send for EntityCommands<'a>
impl<'a> Sync for EntityCommands<'a>
impl<'a> Unpin for EntityCommands<'a>
impl<'a> !UnwindSafe for EntityCommands<'a>
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<GpuImage>) -> U
fn as_bind_group_shader_type(&self, _images: &RenderAssets<GpuImage>) -> 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.Source§impl<T> DowncastSync for T
impl<T> DowncastSync for T
Source§impl<T> FmtForward for T
impl<T> FmtForward for T
Source§fn fmt_binary(self) -> FmtBinary<Self>where
Self: Binary,
fn fmt_binary(self) -> FmtBinary<Self>where
Self: Binary,
self
to use its Binary
implementation when Debug
-formatted.Source§fn fmt_display(self) -> FmtDisplay<Self>where
Self: Display,
fn fmt_display(self) -> FmtDisplay<Self>where
Self: Display,
self
to use its Display
implementation when
Debug
-formatted.Source§fn fmt_lower_exp(self) -> FmtLowerExp<Self>where
Self: LowerExp,
fn fmt_lower_exp(self) -> FmtLowerExp<Self>where
Self: LowerExp,
self
to use its LowerExp
implementation when
Debug
-formatted.Source§fn fmt_lower_hex(self) -> FmtLowerHex<Self>where
Self: LowerHex,
fn fmt_lower_hex(self) -> FmtLowerHex<Self>where
Self: LowerHex,
self
to use its LowerHex
implementation when
Debug
-formatted.Source§fn fmt_octal(self) -> FmtOctal<Self>where
Self: Octal,
fn fmt_octal(self) -> FmtOctal<Self>where
Self: Octal,
self
to use its Octal
implementation when Debug
-formatted.Source§fn fmt_pointer(self) -> FmtPointer<Self>where
Self: Pointer,
fn fmt_pointer(self) -> FmtPointer<Self>where
Self: Pointer,
self
to use its Pointer
implementation when
Debug
-formatted.Source§fn fmt_upper_exp(self) -> FmtUpperExp<Self>where
Self: UpperExp,
fn fmt_upper_exp(self) -> FmtUpperExp<Self>where
Self: UpperExp,
self
to use its UpperExp
implementation when
Debug
-formatted.Source§fn fmt_upper_hex(self) -> FmtUpperHex<Self>where
Self: UpperHex,
fn fmt_upper_hex(self) -> FmtUpperHex<Self>where
Self: UpperHex,
self
to use its UpperHex
implementation when
Debug
-formatted.Source§impl<S> FromSample<S> for S
impl<S> FromSample<S> for S
fn from_sample_(s: S) -> S
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self
into a Left
variant of Either<Self, Self>
if into_left
is true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self
into a Left
variant of Either<Self, Self>
if into_left(&self)
returns true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read moreSource§impl<F, T> IntoSample<T> for Fwhere
T: FromSample<F>,
impl<F, T> IntoSample<T> for Fwhere
T: FromSample<F>,
fn into_sample(self) -> T
Source§impl<T> Pipe for Twhere
T: ?Sized,
impl<T> Pipe for Twhere
T: ?Sized,
Source§fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere
Self: Sized,
fn pipe<R>(self, func: impl FnOnce(Self) -> R) -> Rwhere
Self: Sized,
Source§fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> Rwhere
R: 'a,
fn pipe_ref<'a, R>(&'a self, func: impl FnOnce(&'a Self) -> R) -> Rwhere
R: 'a,
self
and passes that borrow into the pipe function. Read moreSource§fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> Rwhere
R: 'a,
fn pipe_ref_mut<'a, R>(&'a mut self, func: impl FnOnce(&'a mut Self) -> R) -> Rwhere
R: 'a,
self
and passes that borrow into the pipe function. Read moreSource§fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
fn pipe_borrow<'a, B, R>(&'a self, func: impl FnOnce(&'a B) -> R) -> R
Source§fn pipe_borrow_mut<'a, B, R>(
&'a mut self,
func: impl FnOnce(&'a mut B) -> R,
) -> R
fn pipe_borrow_mut<'a, B, R>( &'a mut self, func: impl FnOnce(&'a mut B) -> R, ) -> R
Source§fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
fn pipe_as_ref<'a, U, R>(&'a self, func: impl FnOnce(&'a U) -> R) -> R
self
, then passes self.as_ref()
into the pipe function.Source§fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
fn pipe_as_mut<'a, U, R>(&'a mut self, func: impl FnOnce(&'a mut U) -> R) -> R
self
, then passes self.as_mut()
into the pipe
function.Source§fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
fn pipe_deref<'a, T, R>(&'a self, func: impl FnOnce(&'a T) -> R) -> R
self
, then passes self.deref()
into the pipe function.Source§impl<T> Pointable for T
impl<T> Pointable for T
Source§impl<T> Tap for T
impl<T> Tap for T
Source§fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
fn tap_borrow<B>(self, func: impl FnOnce(&B)) -> Self
Borrow<B>
of a value. Read moreSource§fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
fn tap_borrow_mut<B>(self, func: impl FnOnce(&mut B)) -> Self
BorrowMut<B>
of a value. Read moreSource§fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
fn tap_ref<R>(self, func: impl FnOnce(&R)) -> Self
AsRef<R>
view of a value. Read moreSource§fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
fn tap_ref_mut<R>(self, func: impl FnOnce(&mut R)) -> Self
AsMut<R>
view of a value. Read moreSource§fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
fn tap_deref<T>(self, func: impl FnOnce(&T)) -> Self
Deref::Target
of a value. Read moreSource§fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
fn tap_deref_mut<T>(self, func: impl FnOnce(&mut T)) -> Self
Deref::Target
of a value. Read moreSource§fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self
fn tap_dbg(self, func: impl FnOnce(&Self)) -> Self
.tap()
only in debug builds, and is erased in release builds.Source§fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self
fn tap_mut_dbg(self, func: impl FnOnce(&mut Self)) -> Self
.tap_mut()
only in debug builds, and is erased in release
builds.Source§fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
fn tap_borrow_dbg<B>(self, func: impl FnOnce(&B)) -> Self
.tap_borrow()
only in debug builds, and is erased in release
builds.Source§fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
fn tap_borrow_mut_dbg<B>(self, func: impl FnOnce(&mut B)) -> Self
.tap_borrow_mut()
only in debug builds, and is erased in release
builds.Source§fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
fn tap_ref_dbg<R>(self, func: impl FnOnce(&R)) -> Self
.tap_ref()
only in debug builds, and is erased in release
builds.Source§fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
fn tap_ref_mut_dbg<R>(self, func: impl FnOnce(&mut R)) -> Self
.tap_ref_mut()
only in debug builds, and is erased in release
builds.Source§fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
fn tap_deref_dbg<T>(self, func: impl FnOnce(&T)) -> Self
.tap_deref()
only in debug builds, and is erased in release
builds.