pub struct Query<'world, 'state, D, F = ()>where
D: QueryData,
F: QueryFilter,{ /* private fields */ }
Expand description
System parameter that provides selective access to the Component
data stored in a World
.
Enables access to entity identifiers and components from a system, without the need to directly access the world. Its iterators and getter methods return query items. Each query item is a type containing data relative to an entity.
Query
is a generic data structure that accepts two type parameters:
D
(query data). The type of data contained in the query item. Only entities that match the requested data will generate an item. Must implement theQueryData
trait.F
(query filter). A set of conditions that determines whether query items should be kept or discarded. Must implement theQueryFilter
trait. This type parameter is optional.
§Similar parameters
Query
has few sibling SystemParam
s, which perform additional validation:
Single
- Exactly one matching query item.Option<Single>
- Zero or one matching query item.Populated
- At least one matching query item.
Those parameters will prevent systems from running if their requirements aren’t met.
§System parameter declaration
A query should always be declared as a system parameter.
This section shows the most common idioms involving the declaration of Query
.
§Component access
A query defined with a reference to a component as the query fetch type parameter can be used to generate items that refer to the data of said component.
// A component can be accessed by shared reference...
query: Query<&ComponentA>
// ... or by mutable reference.
query: Query<&mut ComponentA>
§Query filtering
Setting the query filter type parameter will ensure that each query item satisfies the given condition.
// Just `ComponentA` data will be accessed, but only for entities that also contain
// `ComponentB`.
query: Query<&ComponentA, With<ComponentB>>
§QueryData
or QueryFilter
tuples
Using tuples, each Query
type parameter can contain multiple elements.
In the following example, two components are accessed simultaneously, and the query items are filtered on two conditions.
query: Query<(&ComponentA, &ComponentB), (With<ComponentC>, Without<ComponentD>)>
§Entity identifier access
The identifier of an entity can be made available inside the query item by including Entity
in the query fetch type parameter.
query: Query<(Entity, &ComponentA)>
§Optional component access
A component can be made optional in a query by wrapping it into an Option
.
In this way, a query item can still be generated even if the queried entity does not contain the wrapped component.
In this case, its corresponding value will be None
.
// Generates items for entities that contain `ComponentA`, and optionally `ComponentB`.
query: Query<(&ComponentA, Option<&ComponentB>)>
See the documentation for AnyOf
to idiomatically declare many optional components.
See the performance section to learn more about the impact of optional components.
§Disjoint queries
A system cannot contain two queries that break Rust’s mutability rules.
In this case, the Without
filter can be used to disjoint them.
In the following example, two queries mutably access the same component.
Executing this system will panic, since an entity could potentially match the two queries at the same time by having both Player
and Enemy
components.
This would violate mutability rules.
fn randomize_health(
player_query: Query<&mut Health, With<Player>>,
enemy_query: Query<&mut Health, With<Enemy>>,
)
Adding a Without
filter will disjoint the queries.
In this way, any entity that has both Player
and Enemy
components is excluded from both queries.
fn randomize_health(
player_query: Query<&mut Health, (With<Player>, Without<Enemy>)>,
enemy_query: Query<&mut Health, (With<Enemy>, Without<Player>)>,
)
An alternative to this idiom is to wrap the conflicting queries into a ParamSet
.
§Whole Entity Access
EntityRef
s can be fetched from a query. This will give read-only access to any component on the entity,
and can be use to dynamically fetch any component without baking it into the query type. Due to this global
access to the entity, this will block any other system from parallelizing with it. As such these queries
should be sparingly used.
query: Query<(EntityRef, &ComponentA)>
As EntityRef
can read any component on an entity, a query using it will conflict with any mutable
access. It is strongly advised to couple EntityRef
queries with the use of either With
/Without
filters or ParamSets
. This also limits the scope of the query, which will improve iteration performance
and also allows it to parallelize with other non-conflicting systems.
// This will panic!
query: Query<(EntityRef, &mut ComponentA)>
// This will not panic.
query_a: Query<EntityRef, With<ComponentA>>,
query_b: Query<&mut ComponentB, Without<ComponentA>>,
§Accessing query items
The following table summarizes the behavior of the safe methods that can be used to get query items.
Query methods | Effect |
---|---|
iter [_mut ] | Returns an iterator over all query items. |
[iter().for_each() [iter_mut().for_each() ],par_iter [_mut ] | Runs a specified function for each query item. |
iter_many [_mut ] | Iterates or runs a specified function over query items generated by a list of entities. |
iter_combinations [_mut ] | Returns an iterator over all combinations of a specified number of query items. |
get [_mut ] | Returns the query item for the specified entity. |
many [_mut ],get_many [_mut ] | Returns the query items for the specified entities. |
single [_mut ],get_single [_mut ] | Returns the query item while verifying that there aren’t others. |
There are two methods for each type of query operation: immutable and mutable (ending with _mut
).
When using immutable methods, the query items returned are of type ROQueryItem
, a read-only version of the query item.
In this circumstance, every mutable reference in the query fetch type parameter is substituted by a shared reference.
§Performance
Creating a Query
is a low-cost constant operation.
Iterating it, on the other hand, fetches data from the world and generates items, which can have a significant computational cost.
Table
component storage type is much more optimized for query iteration than SparseSet
.
Two systems cannot be executed in parallel if both access the same component type where at least one of the accesses is mutable. This happens unless the executor can verify that no entity could be found in both queries.
Optional components increase the number of entities a query has to match against. This can hurt iteration performance, especially if the query solely consists of only optional components, since the query would iterate over each entity in the world.
The following table compares the computational complexity of the various methods and operations, where:
- n is the number of entities that match the query,
- r is the number of elements in a combination,
- k is the number of involved entities in the operation,
- a is the number of archetypes in the world,
- C is the binomial coefficient, used to count combinations. nCr is read as “n choose r” and is equivalent to the number of distinct unordered subsets of r elements that can be taken from a set of n elements.
Query operation | Computational complexity |
---|---|
iter [_mut ] | O(n) |
[iter().for_each() [iter_mut().for_each() ],par_iter [_mut ] | O(n) |
iter_many [_mut ] | O(k) |
iter_combinations [_mut ] | O(nCr) |
get [_mut ] | O(1) |
(get_ )many | O(k) |
(get_ )many_mut | O(k2) |
single [_mut ],get_single [_mut ] | O(a) |
Archetype based filtering (With , Without , Or ) | O(a) |
Change detection filtering (Added , Changed ) | O(a + n) |
§Iterator::for_each
for_each
methods are seen to be generally faster than directly iterating through iter
on worlds with high archetype
fragmentation, and may enable additional optimizations like autovectorization. It is strongly advised to only use
Iterator::for_each
if it tangibly improves performance. Always be sure profile or benchmark both before and
after the change!
// This might be result in better performance...
query.iter().for_each(|component| {
// do things with the component
});
// ...than this. Always be sure to benchmark to validate the difference!
for component in query.iter() {
// do things with the component
}
Implementations§
Source§impl<'w, 's, D, F> Query<'w, 's, D, F>where
D: QueryData,
F: QueryFilter,
impl<'w, 's, D, F> Query<'w, 's, D, F>where
D: QueryData,
F: QueryFilter,
Sourcepub fn to_readonly(&self) -> Query<'_, 's, <D as QueryData>::ReadOnly, F>
pub fn to_readonly(&self) -> Query<'_, 's, <D as QueryData>::ReadOnly, F>
Returns another Query
from this that fetches the read-only version of the query items.
For example, Query<(&mut D1, &D2, &mut D3), With<F>>
will become Query<(&D1, &D2, &D3), With<F>>
.
This can be useful when working around the borrow checker,
or reusing functionality between systems via functions that accept query types.
Sourcepub fn reborrow(&mut self) -> Query<'_, 's, D, F>
pub fn reborrow(&mut self) -> Query<'_, 's, D, F>
Returns a new Query
reborrowing the access from this one. The current query will be unusable
while the new one exists.
§Example
For example this allows to call other methods or other systems that require an owned Query
without
completely giving up ownership of it.
fn helper_system(query: Query<&ComponentA>) { /* ... */}
fn system(mut query: Query<&ComponentA>) {
helper_system(query.reborrow());
// Can still use query here:
for component in &query {
// ...
}
}
Sourcepub fn iter(&self) -> QueryIter<'_, 's, <D as QueryData>::ReadOnly, F> ⓘ
pub fn iter(&self) -> QueryIter<'_, 's, <D as QueryData>::ReadOnly, F> ⓘ
Returns an Iterator
over the read-only query items.
This iterator is always guaranteed to return results from each matching entity once and only once. Iteration order is not guaranteed.
§Example
Here, the report_names_system
iterates over the Player
component of every entity that contains it:
fn report_names_system(query: Query<&Player>) {
for player in &query {
println!("Say hello to {}!", player.name);
}
}
§See also
iter_mut
for mutable query items.
Examples found in repository?
More examples
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
fn image_copy_extract(mut commands: Commands, image_copiers: Extract<Query<&ImageCopier>>) {
commands.insert_resource(ImageCopiers(
image_copiers.iter().cloned().collect::<Vec<ImageCopier>>(),
));
}
/// `RenderGraph` label for `ImageCopyDriver`
#[derive(Debug, PartialEq, Eq, Clone, Hash, RenderLabel)]
struct ImageCopy;
/// `RenderGraph` node
#[derive(Default)]
struct ImageCopyDriver;
// Copies image content from render target to buffer
impl render_graph::Node for ImageCopyDriver {
fn run(
&self,
_graph: &mut RenderGraphContext,
render_context: &mut RenderContext,
world: &World,
) -> Result<(), NodeRunError> {
let image_copiers = world.get_resource::<ImageCopiers>().unwrap();
let gpu_images = world
.get_resource::<RenderAssets<bevy::render::texture::GpuImage>>()
.unwrap();
for image_copier in image_copiers.iter() {
if !image_copier.enabled() {
continue;
}
let src_image = gpu_images.get(&image_copier.src_image).unwrap();
let mut encoder = render_context
.render_device()
.create_command_encoder(&CommandEncoderDescriptor::default());
let block_dimensions = src_image.texture_format.block_dimensions();
let block_size = src_image.texture_format.block_copy_size(None).unwrap();
// Calculating correct size of image row because
// copy_texture_to_buffer can copy image only by rows aligned wgpu::COPY_BYTES_PER_ROW_ALIGNMENT
// That's why image in buffer can be little bit wider
// This should be taken into account at copy from buffer stage
let padded_bytes_per_row = RenderDevice::align_copy_bytes_per_row(
(src_image.size.x as usize / block_dimensions.0 as usize) * block_size as usize,
);
let texture_extent = Extent3d {
width: src_image.size.x,
height: src_image.size.y,
depth_or_array_layers: 1,
};
encoder.copy_texture_to_buffer(
src_image.texture.as_image_copy(),
ImageCopyBuffer {
buffer: &image_copier.buffer,
layout: ImageDataLayout {
offset: 0,
bytes_per_row: Some(
std::num::NonZero::<u32>::new(padded_bytes_per_row as u32)
.unwrap()
.into(),
),
rows_per_image: None,
},
},
texture_extent,
);
let render_queue = world.get_resource::<RenderQueue>().unwrap();
render_queue.submit(std::iter::once(encoder.finish()));
}
Ok(())
}
}
/// runs in render world after Render stage to send image from buffer via channel (receiver is in main world)
fn receive_image_from_buffer(
image_copiers: Res<ImageCopiers>,
render_device: Res<RenderDevice>,
sender: Res<RenderWorldSender>,
) {
for image_copier in image_copiers.0.iter() {
if !image_copier.enabled() {
continue;
}
// Finally time to get our data back from the gpu.
// First we get a buffer slice which represents a chunk of the buffer (which we
// can't access yet).
// We want the whole thing so use unbounded range.
let buffer_slice = image_copier.buffer.slice(..);
// Now things get complicated. WebGPU, for safety reasons, only allows either the GPU
// or CPU to access a buffer's contents at a time. We need to "map" the buffer which means
// flipping ownership of the buffer over to the CPU and making access legal. We do this
// with `BufferSlice::map_async`.
//
// The problem is that map_async is not an async function so we can't await it. What
// we need to do instead is pass in a closure that will be executed when the slice is
// either mapped or the mapping has failed.
//
// The problem with this is that we don't have a reliable way to wait in the main
// code for the buffer to be mapped and even worse, calling get_mapped_range or
// get_mapped_range_mut prematurely will cause a panic, not return an error.
//
// Using channels solves this as awaiting the receiving of a message from
// the passed closure will force the outside code to wait. It also doesn't hurt
// if the closure finishes before the outside code catches up as the message is
// buffered and receiving will just pick that up.
//
// It may also be worth noting that although on native, the usage of asynchronous
// channels is wholly unnecessary, for the sake of portability to Wasm
// we'll use async channels that work on both native and Wasm.
let (s, r) = crossbeam_channel::bounded(1);
// Maps the buffer so it can be read on the cpu
buffer_slice.map_async(MapMode::Read, move |r| match r {
// This will execute once the gpu is ready, so after the call to poll()
Ok(r) => s.send(r).expect("Failed to send map update"),
Err(err) => panic!("Failed to map buffer {err}"),
});
// In order for the mapping to be completed, one of three things must happen.
// One of those can be calling `Device::poll`. This isn't necessary on the web as devices
// are polled automatically but natively, we need to make sure this happens manually.
// `Maintain::Wait` will cause the thread to wait on native but not on WebGpu.
// This blocks until the gpu is done executing everything
render_device.poll(Maintain::wait()).panic_on_timeout();
// This blocks until the buffer is mapped
r.recv().expect("Failed to receive the map_async message");
// This could fail on app exit, if Main world clears resources (including receiver) while Render world still renders
let _ = sender.send(buffer_slice.get_mapped_range().to_vec());
// We need to make sure all `BufferView`'s are dropped before we do what we're about
// to do.
// Unmap so that we can copy to the staging buffer in the next iteration.
image_copier.buffer.unmap();
}
}
/// CPU-side image for saving
#[derive(Component, Deref, DerefMut)]
struct ImageToSave(Handle<Image>);
// Takes from channel image content sent from render world and saves it to disk
fn update(
images_to_save: Query<&ImageToSave>,
receiver: Res<MainWorldReceiver>,
mut images: ResMut<Assets<Image>>,
mut scene_controller: ResMut<SceneController>,
mut app_exit_writer: EventWriter<AppExit>,
mut file_number: Local<u32>,
) {
if let SceneState::Render(n) = scene_controller.state {
if n < 1 {
// We don't want to block the main world on this,
// so we use try_recv which attempts to receive without blocking
let mut image_data = Vec::new();
while let Ok(data) = receiver.try_recv() {
// image generation could be faster than saving to fs,
// that's why use only last of them
image_data = data;
}
if !image_data.is_empty() {
for image in images_to_save.iter() {
// Fill correct data from channel to image
let img_bytes = images.get_mut(image.id()).unwrap();
// We need to ensure that this works regardless of the image dimensions
// If the image became wider when copying from the texture to the buffer,
// then the data is reduced to its original size when copying from the buffer to the image.
let row_bytes = img_bytes.width() as usize
* img_bytes.texture_descriptor.format.pixel_size();
let aligned_row_bytes = RenderDevice::align_copy_bytes_per_row(row_bytes);
if row_bytes == aligned_row_bytes {
img_bytes.data.clone_from(&image_data);
} else {
// shrink data to original image size
img_bytes.data = image_data
.chunks(aligned_row_bytes)
.take(img_bytes.height() as usize)
.flat_map(|row| &row[..row_bytes.min(row.len())])
.cloned()
.collect();
}
// Create RGBA Image Buffer
let img = match img_bytes.clone().try_into_dynamic() {
Ok(img) => img.to_rgba8(),
Err(e) => panic!("Failed to create image buffer {e:?}"),
};
// Prepare directory for images, test_images in bevy folder is used here for example
// You should choose the path depending on your needs
let images_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("test_images");
info!("Saving image to: {images_dir:?}");
std::fs::create_dir_all(&images_dir).unwrap();
// Choose filename starting from 000.png
let image_path = images_dir.join(format!("{:03}.png", file_number.deref()));
*file_number.deref_mut() += 1;
// Finally saving image to file, this heavy blocking operation is kept here
// for example simplicity, but in real app you should move it to a separate task
if let Err(e) = img.save(image_path) {
panic!("Failed to save image: {e}");
};
}
if scene_controller.single_image {
app_exit_writer.send(AppExit::Success);
}
}
} else {
// clears channel for skipped frames
while receiver.try_recv().is_ok() {}
scene_controller.state = SceneState::Render(n - 1);
}
}
}
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
fn print_light_count(time: Res<Time>, mut timer: Local<PrintingTimer>, lights: Query<&PointLight>) {
timer.0.tick(time.delta());
if timer.0.just_finished() {
info!("Lights: {}", lights.iter().len());
}
}
struct LogVisibleLights;
impl Plugin for LogVisibleLights {
fn build(&self, app: &mut App) {
let Some(render_app) = app.get_sub_app_mut(RenderApp) else {
return;
};
render_app.add_systems(Render, print_visible_light_count.in_set(RenderSet::Prepare));
}
}
// System for printing the number of meshes on every tick of the timer
fn print_visible_light_count(
time: Res<Time>,
mut timer: Local<PrintingTimer>,
visible: Query<&ExtractedPointLight>,
global_light_meta: Res<GlobalClusterableObjectMeta>,
) {
timer.0.tick(time.delta());
if timer.0.just_finished() {
info!(
"Visible Lights: {}, Rendered Lights: {}",
visible.iter().len(),
global_light_meta.entity_to_index.len()
);
}
}
- examples/games/loading_screen.rs
- examples/ecs/observer_propagation.rs
- examples/ecs/removal_detection.rs
- examples/stress_tests/many_cubes.rs
- examples/asset/multi_asset_sync.rs
- examples/picking/mesh_picking.rs
- examples/3d/animated_material.rs
- examples/3d/reflection_probes.rs
- examples/3d/depth_of_field.rs
- examples/window/screenshot.rs
- examples/asset/asset_decompression.rs
- examples/stress_tests/many_foxes.rs
- examples/3d/anisotropy.rs
- examples/math/sampling_primitives.rs
- examples/3d/irradiance_volumes.rs
- examples/2d/bounding_2d.rs
- examples/3d/shadow_caster_receiver.rs
- examples/ecs/fallible_params.rs
- examples/math/custom_primitives.rs
- examples/3d/load_gltf_extras.rs
- examples/animation/animation_graph.rs
- examples/3d/lightmaps.rs
- examples/3d/query_gltf_primitives.rs
- examples/math/render_primitives.rs
- examples/audio/soundtrack.rs
- examples/ui/size_constraints.rs
- examples/3d/color_grading.rs
- examples/window/monitor_info.rs
- examples/shader/custom_phase_item.rs
- examples/shader/specialized_mesh_pipeline.rs
Sourcepub fn iter_mut(&mut self) -> QueryIter<'_, 's, D, F> ⓘ
pub fn iter_mut(&mut self) -> QueryIter<'_, 's, D, F> ⓘ
Returns an Iterator
over the query items.
This iterator is always guaranteed to return results from each matching entity once and only once. Iteration order is not guaranteed.
§Example
Here, the gravity_system
updates the Velocity
component of every entity that contains it:
fn gravity_system(mut query: Query<&mut Velocity>) {
const DELTA: f32 = 1.0 / 60.0;
for mut velocity in &mut query {
velocity.y -= 9.8 * DELTA;
}
}
§See also
iter
for read-only query items.
Examples found in repository?
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 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
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);
}
}
}
}
}
// Draws a gizmo showing the bounds of the irradiance volume.
fn draw_gizmo(
mut gizmos: Gizmos,
irradiance_volume_query: Query<&GlobalTransform, With<IrradianceVolume>>,
app_status: Res<AppStatus>,
) {
if app_status.voxels_visible {
for transform in irradiance_volume_query.iter() {
gizmos.cuboid(*transform, GIZMO_COLOR);
}
}
}
// Handles a request from the user to toggle the voxel visibility on and off.
fn toggle_voxel_visibility(
keyboard: Res<ButtonInput<KeyCode>>,
mut app_status: ResMut<AppStatus>,
mut voxel_cube_parent_query: Query<&mut Visibility, With<VoxelCubeParent>>,
) {
if !keyboard.just_pressed(KeyCode::Backspace) {
return;
}
app_status.voxels_visible = !app_status.voxels_visible;
for mut visibility in voxel_cube_parent_query.iter_mut() {
*visibility = if app_status.voxels_visible {
Visibility::Visible
} else {
Visibility::Hidden
};
}
}
More examples
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
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 TryFrom<u32> for ReflectionMode {
type Error = ();
fn try_from(value: u32) -> Result<Self, Self::Error> {
match value {
0 => Ok(ReflectionMode::None),
1 => Ok(ReflectionMode::EnvironmentMap),
2 => Ok(ReflectionMode::ReflectionProbe),
_ => Err(()),
}
}
}
impl Display for ReflectionMode {
fn fmt(&self, formatter: &mut Formatter<'_>) -> FmtResult {
let text = match *self {
ReflectionMode::None => "No reflections",
ReflectionMode::EnvironmentMap => "Environment map",
ReflectionMode::ReflectionProbe => "Reflection probe",
};
formatter.write_str(text)
}
}
impl AppStatus {
// Constructs the help text at the bottom of the screen based on the
// application status.
fn create_text(&self) -> Text {
let rotation_help_text = if self.rotating {
STOP_ROTATION_HELP_TEXT
} else {
START_ROTATION_HELP_TEXT
};
format!(
"{}\n{}\n{}",
self.reflection_mode, rotation_help_text, REFLECTION_MODE_HELP_TEXT
)
.into()
}
}
// Creates the world environment map light, used as a fallback if no reflection
// probe is applicable to a mesh.
fn create_camera_environment_map_light(cubemaps: &Cubemaps) -> EnvironmentMapLight {
EnvironmentMapLight {
diffuse_map: cubemaps.diffuse.clone(),
specular_map: cubemaps.specular_environment_map.clone(),
intensity: 5000.0,
..default()
}
}
// Rotates the camera a bit every frame.
fn rotate_camera(
time: Res<Time>,
mut camera_query: Query<&mut Transform, With<Camera3d>>,
app_status: Res<AppStatus>,
) {
if !app_status.rotating {
return;
}
for mut transform in camera_query.iter_mut() {
transform.translation = Vec2::from_angle(time.delta_secs() * PI / 5.0)
.rotate(transform.translation.xz())
.extend(transform.translation.y)
.xzy();
transform.look_at(Vec3::ZERO, Vec3::Y);
}
}
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 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 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 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 407 408 409 410 411 412 413 414 415 416
fn spin(time: Res<Time>, mut query: Query<&mut Transform, With<Spin>>) {
for mut transform in query.iter_mut() {
transform.rotation *= Quat::from_rotation_z(time.delta_secs() / 5.);
}
}
#[derive(States, Default, Debug, Hash, PartialEq, Eq, Clone, Copy)]
enum Test {
AabbSweep,
CircleSweep,
#[default]
RayCast,
AabbCast,
CircleCast,
}
fn update_test_state(
keycode: Res<ButtonInput<KeyCode>>,
cur_state: Res<State<Test>>,
mut state: ResMut<NextState<Test>>,
) {
if !keycode.just_pressed(KeyCode::Space) {
return;
}
use Test::*;
let next = match **cur_state {
AabbSweep => CircleSweep,
CircleSweep => RayCast,
RayCast => AabbCast,
AabbCast => CircleCast,
CircleCast => AabbSweep,
};
state.set(next);
}
fn update_text(mut text: Single<&mut Text>, cur_state: Res<State<Test>>) {
if !cur_state.is_changed() {
return;
}
text.clear();
text.push_str("Intersection test:\n");
use Test::*;
for &test in &[AabbSweep, CircleSweep, RayCast, AabbCast, CircleCast] {
let s = if **cur_state == test { "*" } else { " " };
text.push_str(&format!(" {s} {test:?} {s}\n"));
}
text.push_str("\nPress space to cycle");
}
#[derive(Component)]
enum Shape {
Rectangle(Rectangle),
Circle(Circle),
Triangle(Triangle2d),
Line(Segment2d),
Capsule(Capsule2d),
Polygon(RegularPolygon),
}
fn render_shapes(mut gizmos: Gizmos, query: Query<(&Shape, &Transform)>) {
let color = GRAY;
for (shape, transform) in query.iter() {
let translation = transform.translation.xy();
let rotation = transform.rotation.to_euler(EulerRot::YXZ).2;
let isometry = Isometry2d::new(translation, Rot2::radians(rotation));
match shape {
Shape::Rectangle(r) => {
gizmos.primitive_2d(r, isometry, color);
}
Shape::Circle(c) => {
gizmos.primitive_2d(c, isometry, color);
}
Shape::Triangle(t) => {
gizmos.primitive_2d(t, isometry, color);
}
Shape::Line(l) => {
gizmos.primitive_2d(l, isometry, color);
}
Shape::Capsule(c) => {
gizmos.primitive_2d(c, isometry, color);
}
Shape::Polygon(p) => {
gizmos.primitive_2d(p, isometry, color);
}
}
}
}
#[derive(Component)]
enum DesiredVolume {
Aabb,
Circle,
}
#[derive(Component, Debug)]
enum CurrentVolume {
Aabb(Aabb2d),
Circle(BoundingCircle),
}
fn update_volumes(
mut commands: Commands,
query: Query<
(Entity, &DesiredVolume, &Shape, &Transform),
Or<(Changed<DesiredVolume>, Changed<Shape>, Changed<Transform>)>,
>,
) {
for (entity, desired_volume, shape, transform) in query.iter() {
let translation = transform.translation.xy();
let rotation = transform.rotation.to_euler(EulerRot::YXZ).2;
let isometry = Isometry2d::new(translation, Rot2::radians(rotation));
match desired_volume {
DesiredVolume::Aabb => {
let aabb = match shape {
Shape::Rectangle(r) => r.aabb_2d(isometry),
Shape::Circle(c) => c.aabb_2d(isometry),
Shape::Triangle(t) => t.aabb_2d(isometry),
Shape::Line(l) => l.aabb_2d(isometry),
Shape::Capsule(c) => c.aabb_2d(isometry),
Shape::Polygon(p) => p.aabb_2d(isometry),
};
commands.entity(entity).insert(CurrentVolume::Aabb(aabb));
}
DesiredVolume::Circle => {
let circle = match shape {
Shape::Rectangle(r) => r.bounding_circle(isometry),
Shape::Circle(c) => c.bounding_circle(isometry),
Shape::Triangle(t) => t.bounding_circle(isometry),
Shape::Line(l) => l.bounding_circle(isometry),
Shape::Capsule(c) => c.bounding_circle(isometry),
Shape::Polygon(p) => p.bounding_circle(isometry),
};
commands
.entity(entity)
.insert(CurrentVolume::Circle(circle));
}
}
}
}
fn render_volumes(mut gizmos: Gizmos, query: Query<(&CurrentVolume, &Intersects)>) {
for (volume, intersects) in query.iter() {
let color = if **intersects { AQUA } else { ORANGE_RED };
match volume {
CurrentVolume::Aabb(a) => {
gizmos.rect_2d(a.center(), a.half_size() * 2., color);
}
CurrentVolume::Circle(c) => {
gizmos.circle_2d(c.center(), c.radius(), color);
}
}
}
}
#[derive(Component, Deref, DerefMut, Default)]
struct Intersects(bool);
const OFFSET_X: f32 = 125.;
const OFFSET_Y: f32 = 75.;
fn setup(mut commands: Commands) {
commands.spawn(Camera2d);
commands.spawn((
Transform::from_xyz(-OFFSET_X, OFFSET_Y, 0.),
Shape::Circle(Circle::new(45.)),
DesiredVolume::Aabb,
Intersects::default(),
));
commands.spawn((
Transform::from_xyz(0., OFFSET_Y, 0.),
Shape::Rectangle(Rectangle::new(80., 80.)),
Spin,
DesiredVolume::Circle,
Intersects::default(),
));
commands.spawn((
Transform::from_xyz(OFFSET_X, OFFSET_Y, 0.),
Shape::Triangle(Triangle2d::new(
Vec2::new(-40., -40.),
Vec2::new(-20., 40.),
Vec2::new(40., 50.),
)),
Spin,
DesiredVolume::Aabb,
Intersects::default(),
));
commands.spawn((
Transform::from_xyz(-OFFSET_X, -OFFSET_Y, 0.),
Shape::Line(Segment2d::new(Dir2::from_xy(1., 0.3).unwrap(), 90.)),
Spin,
DesiredVolume::Circle,
Intersects::default(),
));
commands.spawn((
Transform::from_xyz(0., -OFFSET_Y, 0.),
Shape::Capsule(Capsule2d::new(25., 50.)),
Spin,
DesiredVolume::Aabb,
Intersects::default(),
));
commands.spawn((
Transform::from_xyz(OFFSET_X, -OFFSET_Y, 0.),
Shape::Polygon(RegularPolygon::new(50., 6)),
Spin,
DesiredVolume::Circle,
Intersects::default(),
));
commands.spawn((
Text::default(),
Node {
position_type: PositionType::Absolute,
bottom: Val::Px(12.0),
left: Val::Px(12.0),
..default()
},
));
}
fn draw_filled_circle(gizmos: &mut Gizmos, position: Vec2, color: Srgba) {
for r in [1., 2., 3.] {
gizmos.circle_2d(position, r, color);
}
}
fn draw_ray(gizmos: &mut Gizmos, ray: &RayCast2d) {
gizmos.line_2d(
ray.ray.origin,
ray.ray.origin + *ray.ray.direction * ray.max,
WHITE,
);
draw_filled_circle(gizmos, ray.ray.origin, FUCHSIA);
}
fn get_and_draw_ray(gizmos: &mut Gizmos, time: &Time) -> RayCast2d {
let ray = Vec2::new(ops::cos(time.elapsed_secs()), ops::sin(time.elapsed_secs()));
let dist = 150. + ops::sin(0.5 * time.elapsed_secs()).abs() * 500.;
let aabb_ray = Ray2d {
origin: ray * 250.,
direction: Dir2::new_unchecked(-ray),
};
let ray_cast = RayCast2d::from_ray(aabb_ray, dist - 20.);
draw_ray(gizmos, &ray_cast);
ray_cast
}
fn ray_cast_system(
mut gizmos: Gizmos,
time: Res<Time>,
mut volumes: Query<(&CurrentVolume, &mut Intersects)>,
) {
let ray_cast = get_and_draw_ray(&mut gizmos, &time);
for (volume, mut intersects) in volumes.iter_mut() {
let toi = match volume {
CurrentVolume::Aabb(a) => ray_cast.aabb_intersection_at(a),
CurrentVolume::Circle(c) => ray_cast.circle_intersection_at(c),
};
**intersects = toi.is_some();
if let Some(toi) = toi {
draw_filled_circle(
&mut gizmos,
ray_cast.ray.origin + *ray_cast.ray.direction * toi,
LIME,
);
}
}
}
fn aabb_cast_system(
mut gizmos: Gizmos,
time: Res<Time>,
mut volumes: Query<(&CurrentVolume, &mut Intersects)>,
) {
let ray_cast = get_and_draw_ray(&mut gizmos, &time);
let aabb_cast = AabbCast2d {
aabb: Aabb2d::new(Vec2::ZERO, Vec2::splat(15.)),
ray: ray_cast,
};
for (volume, mut intersects) in volumes.iter_mut() {
let toi = match *volume {
CurrentVolume::Aabb(a) => aabb_cast.aabb_collision_at(a),
CurrentVolume::Circle(_) => None,
};
**intersects = toi.is_some();
if let Some(toi) = toi {
gizmos.rect_2d(
aabb_cast.ray.ray.origin + *aabb_cast.ray.ray.direction * toi,
aabb_cast.aabb.half_size() * 2.,
LIME,
);
}
}
}
fn bounding_circle_cast_system(
mut gizmos: Gizmos,
time: Res<Time>,
mut volumes: Query<(&CurrentVolume, &mut Intersects)>,
) {
let ray_cast = get_and_draw_ray(&mut gizmos, &time);
let circle_cast = BoundingCircleCast {
circle: BoundingCircle::new(Vec2::ZERO, 15.),
ray: ray_cast,
};
for (volume, mut intersects) in volumes.iter_mut() {
let toi = match *volume {
CurrentVolume::Aabb(_) => None,
CurrentVolume::Circle(c) => circle_cast.circle_collision_at(c),
};
**intersects = toi.is_some();
if let Some(toi) = toi {
gizmos.circle_2d(
circle_cast.ray.ray.origin + *circle_cast.ray.ray.direction * toi,
circle_cast.circle.radius(),
LIME,
);
}
}
}
fn get_intersection_position(time: &Time) -> Vec2 {
let x = ops::cos(0.8 * time.elapsed_secs()) * 250.;
let y = ops::sin(0.4 * time.elapsed_secs()) * 100.;
Vec2::new(x, y)
}
fn aabb_intersection_system(
mut gizmos: Gizmos,
time: Res<Time>,
mut volumes: Query<(&CurrentVolume, &mut Intersects)>,
) {
let center = get_intersection_position(&time);
let aabb = Aabb2d::new(center, Vec2::splat(50.));
gizmos.rect_2d(center, aabb.half_size() * 2., YELLOW);
for (volume, mut intersects) in volumes.iter_mut() {
let hit = match volume {
CurrentVolume::Aabb(a) => aabb.intersects(a),
CurrentVolume::Circle(c) => aabb.intersects(c),
};
**intersects = hit;
}
}
fn circle_intersection_system(
mut gizmos: Gizmos,
time: Res<Time>,
mut volumes: Query<(&CurrentVolume, &mut Intersects)>,
) {
let center = get_intersection_position(&time);
let circle = BoundingCircle::new(center, 50.);
gizmos.circle_2d(center, circle.radius(), YELLOW);
for (volume, mut intersects) in volumes.iter_mut() {
let hit = match volume {
CurrentVolume::Aabb(a) => circle.intersects(a),
CurrentVolume::Circle(c) => circle.intersects(c),
};
**intersects = hit;
}
}
- examples/shader/shader_prepass.rs
- examples/stress_tests/text_pipeline.rs
- examples/math/custom_primitives.rs
- examples/3d/bloom_3d.rs
- examples/3d/ssr.rs
- examples/3d/fog_volumes.rs
- examples/3d/parallax_mapping.rs
- examples/3d/anisotropy.rs
- examples/3d/volumetric_fog.rs
- examples/math/cubic_splines.rs
- examples/3d/rotate_environment_map.rs
- examples/3d/camera_sub_view.rs
- examples/3d/deferred_rendering.rs
- examples/input/text_input.rs
- examples/audio/soundtrack.rs
- examples/ui/overflow.rs
- examples/3d/clearcoat.rs
- examples/3d/color_grading.rs
- examples/3d/../helpers/widgets.rs
- examples/time/virtual_time.rs
- examples/3d/spotlight.rs
- examples/stress_tests/many_animated_sprites.rs
- examples/animation/animation_graph.rs
- examples/ui/viewport_debug.rs
- examples/audio/spatial_audio_2d.rs
- examples/3d/tonemapping.rs
- examples/audio/spatial_audio_3d.rs
- examples/math/render_primitives.rs
- examples/window/window_drag_move.rs
- examples/3d/depth_of_field.rs
- examples/3d/pcss.rs
- examples/ui/display_and_visibility.rs
- examples/movement/physics_in_fixed_timestep.rs
- examples/3d/visibility_range.rs
- examples/stress_tests/many_buttons.rs
- examples/animation/animation_masks.rs
- examples/games/alien_cake_addict.rs
- examples/camera/2d_screen_shake.rs
- examples/ui/size_constraints.rs
- examples/math/sampling_primitives.rs
Sourcepub fn iter_combinations<const K: usize>(
&self,
) -> QueryCombinationIter<'_, 's, <D as QueryData>::ReadOnly, F, K> ⓘ
pub fn iter_combinations<const K: usize>( &self, ) -> QueryCombinationIter<'_, 's, <D as QueryData>::ReadOnly, F, K> ⓘ
Returns a QueryCombinationIter
over all combinations of K
read-only query items without repetition.
This iterator is always guaranteed to return results from each unique pair of matching entities. Iteration order is not guaranteed.
§Example
fn some_system(query: Query<&ComponentA>) {
for [a1, a2] in query.iter_combinations() {
// ...
}
}
§See also
iter_combinations_mut
for mutable query item combinations.
Sourcepub fn iter_combinations_mut<const K: usize>(
&mut self,
) -> QueryCombinationIter<'_, 's, D, F, K> ⓘ
pub fn iter_combinations_mut<const K: usize>( &mut self, ) -> QueryCombinationIter<'_, 's, D, F, K> ⓘ
Returns a QueryCombinationIter
over all combinations of K
query items without repetition.
This iterator is always guaranteed to return results from each unique pair of matching entities. Iteration order is not guaranteed.
§Example
fn some_system(mut query: Query<&mut ComponentA>) {
let mut combinations = query.iter_combinations_mut();
while let Some([mut a1, mut a2]) = combinations.fetch_next() {
// mutably access components data
}
}
§See also
iter_combinations
for read-only query item combinations.
Examples found in repository?
122 123 124 125 126 127 128 129 130 131 132 133 134 135
fn interact_bodies(mut query: Query<(&Mass, &GlobalTransform, &mut Acceleration)>) {
let mut iter = query.iter_combinations_mut();
while let Some([(Mass(m1), transform1, mut acc1), (Mass(m2), transform2, mut acc2)]) =
iter.fetch_next()
{
let delta = transform2.translation() - transform1.translation();
let distance_sq: f32 = delta.length_squared();
let f = GRAVITY_CONSTANT / distance_sq;
let force_unit_mass = delta * f;
acc1.0 += force_unit_mass * *m2;
acc2.0 -= force_unit_mass * *m1;
}
}
Sourcepub fn iter_many<EntityList>(
&self,
entities: EntityList,
) -> QueryManyIter<'_, 's, <D as QueryData>::ReadOnly, F, <EntityList as IntoIterator>::IntoIter> ⓘ
pub fn iter_many<EntityList>( &self, entities: EntityList, ) -> QueryManyIter<'_, 's, <D as QueryData>::ReadOnly, F, <EntityList as IntoIterator>::IntoIter> ⓘ
Returns an Iterator
over the read-only query items generated from an Entity
list.
Items are returned in the order of the list of entities, and may not be unique if the input doesn’t guarantee uniqueness. Entities that don’t match the query are skipped.
§Example
// A component containing an entity list.
#[derive(Component)]
struct Friends {
list: Vec<Entity>,
}
fn system(
friends_query: Query<&Friends>,
counter_query: Query<&Counter>,
) {
for friends in &friends_query {
for counter in counter_query.iter_many(&friends.list) {
println!("Friend's counter: {:?}", counter.value);
}
}
}
§See also
iter_many_mut
to get mutable query items.
Sourcepub fn iter_many_mut<EntityList>(
&mut self,
entities: EntityList,
) -> QueryManyIter<'_, 's, D, F, <EntityList as IntoIterator>::IntoIter> ⓘ
pub fn iter_many_mut<EntityList>( &mut self, entities: EntityList, ) -> QueryManyIter<'_, 's, D, F, <EntityList as IntoIterator>::IntoIter> ⓘ
Returns an iterator over the query items generated from an Entity
list.
Items are returned in the order of the list of entities, and may not be unique if the input doesnn’t guarantee uniqueness. Entities that don’t match the query are skipped.
§Examples
#[derive(Component)]
struct Counter {
value: i32
}
#[derive(Component)]
struct Friends {
list: Vec<Entity>,
}
fn system(
friends_query: Query<&Friends>,
mut counter_query: Query<&mut Counter>,
) {
for friends in &friends_query {
let mut iter = counter_query.iter_many_mut(&friends.list);
while let Some(mut counter) = iter.fetch_next() {
println!("Friend's counter: {:?}", counter.value);
counter.value += 1;
}
}
}
Examples found in repository?
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
fn update_ui(
mut text_query: Query<&mut Text>,
mut background_query: Query<&mut Node, Without<Text>>,
container_query: Query<(&Children, &ClipNode)>,
animation_weights_query: Query<&ExampleAnimationWeights, Changed<ExampleAnimationWeights>>,
) {
for animation_weights in animation_weights_query.iter() {
for (children, clip_node) in &container_query {
// Draw the green background color to visually indicate the weight.
let mut bg_iter = background_query.iter_many_mut(children);
if let Some(mut node) = bg_iter.fetch_next() {
// All nodes are the same width, so `NODE_RECTS[0]` is as good as any other.
node.width =
Val::Px(NODE_RECTS[0].width * animation_weights.weights[clip_node.index]);
}
// Update the node labels with the current weights.
let mut text_iter = text_query.iter_many_mut(children);
if let Some(mut text) = text_iter.fetch_next() {
**text = format!(
"{}\n{:.2}",
clip_node.text, animation_weights.weights[clip_node.index]
);
}
}
}
}
Sourcepub unsafe fn iter_unsafe(&self) -> QueryIter<'_, 's, D, F> ⓘ
pub unsafe fn iter_unsafe(&self) -> QueryIter<'_, 's, D, F> ⓘ
Returns an Iterator
over the query items.
This iterator is always guaranteed to return results from each matching entity once and only once. Iteration order is not guaranteed.
§Safety
This function makes it possible to violate Rust’s aliasing guarantees. You must make sure this call does not result in multiple mutable references to the same component.
§See also
Sourcepub unsafe fn iter_combinations_unsafe<const K: usize>(
&self,
) -> QueryCombinationIter<'_, 's, D, F, K> ⓘ
pub unsafe fn iter_combinations_unsafe<const K: usize>( &self, ) -> QueryCombinationIter<'_, 's, D, F, K> ⓘ
Iterates over all possible combinations of K
query items without repetition.
This iterator is always guaranteed to return results from each unique pair of matching entities. Iteration order is not guaranteed.
§Safety
This allows aliased mutability. You must make sure this call does not result in multiple mutable references to the same component.
§See also
iter_combinations
anditer_combinations_mut
for the safe versions.
Sourcepub unsafe fn iter_many_unsafe<EntityList>(
&self,
entities: EntityList,
) -> QueryManyIter<'_, 's, D, F, <EntityList as IntoIterator>::IntoIter> ⓘ
pub unsafe fn iter_many_unsafe<EntityList>( &self, entities: EntityList, ) -> QueryManyIter<'_, 's, D, F, <EntityList as IntoIterator>::IntoIter> ⓘ
Returns an Iterator
over the query items generated from an Entity
list.
Items are returned in the order of the list of entities, and may not be unique if the input doesnn’t guarantee uniqueness. Entities that don’t match the query are skipped.
§Safety
This allows aliased mutability and does not check for entity uniqueness.
You must make sure this call does not result in multiple mutable references to the same component.
Particular care must be taken when collecting the data (rather than iterating over it one item at a time) such as via Iterator::collect
.
§See also
iter_many_mut
to safely access the query items.
Sourcepub fn par_iter(&self) -> QueryParIter<'_, '_, <D as QueryData>::ReadOnly, F>
pub fn par_iter(&self) -> QueryParIter<'_, '_, <D as QueryData>::ReadOnly, F>
Returns a parallel iterator over the query results for the given World
.
This parallel iterator is always guaranteed to return results from each matching entity once and only once. Iteration order and thread assignment is not guaranteed.
If the multithreaded
feature is disabled, iterating with this operates identically to Iterator::for_each
on QueryIter
.
This can only be called for read-only queries, see par_iter_mut
for write-queries.
Note that you must use the for_each
method to iterate over the
results, see par_iter_mut
for an example.
Sourcepub fn par_iter_mut(&mut self) -> QueryParIter<'_, '_, D, F>
pub fn par_iter_mut(&mut self) -> QueryParIter<'_, '_, D, F>
Returns a parallel iterator over the query results for the given World
.
This parallel iterator is always guaranteed to return results from each matching entity once and only once. Iteration order and thread assignment is not guaranteed.
If the multithreaded
feature is disabled, iterating with this operates identically to Iterator::for_each
on QueryIter
.
This can only be called for mutable queries, see par_iter
for read-only-queries.
§Example
Here, the gravity_system
updates the Velocity
component of every entity that contains it:
fn gravity_system(mut query: Query<&mut Velocity>) {
const DELTA: f32 = 1.0 / 60.0;
query.par_iter_mut().for_each(|mut velocity| {
velocity.y -= 9.8 * DELTA;
});
}
Examples found in repository?
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
fn move_system(mut sprites: Query<(&mut Transform, &Velocity)>) {
// Compute the new location of each sprite in parallel on the
// ComputeTaskPool
//
// This example is only for demonstrative purposes. Using a
// ParallelIterator for an inexpensive operation like addition on only 128
// elements will not typically be faster than just using a normal Iterator.
// See the ParallelIterator documentation for more information on when
// to use or not use ParallelIterator over a normal Iterator.
sprites
.par_iter_mut()
.for_each(|(mut transform, velocity)| {
transform.translation += velocity.extend(0.0);
});
}
// Bounce sprites outside the window
fn bounce_system(window: Single<&Window>, mut sprites: Query<(&Transform, &mut Velocity)>) {
let width = window.width();
let height = window.height();
let left = width / -2.0;
let right = width / 2.0;
let bottom = height / -2.0;
let top = height / 2.0;
// The default batch size can also be overridden.
// In this case a batch size of 32 is chosen to limit the overhead of
// ParallelIterator, since negating a vector is very inexpensive.
sprites
.par_iter_mut()
.batching_strategy(BatchingStrategy::fixed(32))
.for_each(|(transform, mut v)| {
if !(left < transform.translation.x
&& transform.translation.x < right
&& bottom < transform.translation.y
&& transform.translation.y < top)
{
// For simplicity, just reverse the velocity; don't use realistic bounces
v.0 = -v.0;
}
});
}
Sourcepub fn get(
&self,
entity: Entity,
) -> Result<<<D as QueryData>::ReadOnly as WorldQuery>::Item<'_>, QueryEntityError<'_>>
pub fn get( &self, entity: Entity, ) -> Result<<<D as QueryData>::ReadOnly as WorldQuery>::Item<'_>, QueryEntityError<'_>>
Returns the read-only query item for the given Entity
.
In case of a nonexisting entity or mismatched component, a QueryEntityError
is returned instead.
This is always guaranteed to run in O(1)
time.
§Example
Here, get
is used to retrieve the exact query item of the entity specified by the SelectedCharacter
resource.
fn print_selected_character_name_system(
query: Query<&Character>,
selection: Res<SelectedCharacter>
)
{
if let Ok(selected_character) = query.get(selection.entity) {
println!("{}", selected_character.name);
}
}
§See also
get_mut
to get a mutable query item.
Examples found in repository?
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
fn attack_hits(trigger: Trigger<Attack>, name: Query<&Name>) {
if let Ok(name) = name.get(trigger.entity()) {
info!("Attack hit {}", name);
}
}
/// A callback placed on [`Armor`], checking if it absorbed all the [`Attack`] damage.
fn block_attack(mut trigger: Trigger<Attack>, armor: Query<(&Armor, &Name)>) {
let (armor, name) = armor.get(trigger.entity()).unwrap();
let attack = trigger.event_mut();
let damage = attack.damage.saturating_sub(**armor);
if damage > 0 {
info!("🩸 {} damage passed through {}", damage, name);
// The attack isn't stopped by the armor. We reduce the damage of the attack, and allow
// it to continue on to the goblin.
attack.damage = damage;
} else {
info!("🛡️ {} damage blocked by {}", attack.damage, name);
// Armor stopped the attack, the event stops here.
trigger.propagate(false);
info!("(propagation halted early)\n");
}
}
More examples
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
fn pause_animation_frame(
trigger: Trigger<SceneInstanceReady>,
children: Query<&Children>,
mut commands: Commands,
animation: Res<Animation>,
mut players: Query<(Entity, &mut AnimationPlayer)>,
) {
let entity = children.get(trigger.entity()).unwrap()[0];
let entity = children.get(entity).unwrap()[0];
let (entity, mut player) = players.get_mut(entity).unwrap();
let mut transitions = AnimationTransitions::new();
transitions
.play(&mut player, animation.animation, Duration::ZERO)
.seek_to(0.5)
.pause();
commands
.entity(entity)
.insert(AnimationGraphHandle(animation.graph.clone()))
.insert(transitions);
}
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
fn observe_on_step(
trigger: Trigger<OnStep>,
particle: Res<ParticleAssets>,
mut commands: Commands,
transforms: Query<&GlobalTransform>,
) {
let translation = transforms.get(trigger.entity()).unwrap().translation();
let mut rng = thread_rng();
// Spawn a bunch of particles.
for _ in 0..14 {
let horizontal = rng.gen::<Dir2>() * rng.gen_range(8.0..12.0);
let vertical = rng.gen_range(0.0..4.0);
let size = rng.gen_range(0.2..1.0);
commands.queue(spawn_particle(
particle.mesh.clone(),
particle.material.clone(),
translation.reject_from_normalized(Vec3::Y),
rng.gen_range(0.2..0.6),
size,
Vec3::new(horizontal.x, vertical, horizontal.y) * 10.0,
));
}
}
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
fn button_system(
mut interaction_query: Query<(&Interaction, &Parent), (Changed<Interaction>, With<Button>)>,
labels_query: Query<(&Children, &Parent), With<Button>>,
mut text_query: Query<&mut Text>,
mut counter_query: Query<&mut Counter>,
) {
// Update parent counter on click
for (interaction, parent) in &mut interaction_query {
if matches!(interaction, Interaction::Pressed) {
let mut counter = counter_query.get_mut(parent.get()).unwrap();
counter.0 += 1;
}
}
// Update button labels to match their parent counter
for (children, parent) in &labels_query {
let counter = counter_query.get(parent.get()).unwrap();
let mut text = text_query.get_mut(children[0]).unwrap();
**text = counter.0.to_string();
}
}
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
fn update_ui(
mut animation_controls: Query<(&AnimationControl, &mut BackgroundColor, &Children)>,
texts: Query<Entity, With<Text>>,
mut writer: TextUiWriter,
app_state: Res<AppState>,
) {
for (animation_control, mut background_color, kids) in animation_controls.iter_mut() {
let enabled =
app_state.0[animation_control.group_id as usize].clip == animation_control.label as u8;
*background_color = if enabled {
BackgroundColor(Color::WHITE)
} else {
BackgroundColor(Color::BLACK)
};
for &kid in kids {
let Ok(text) = texts.get(kid) else {
continue;
};
writer.for_each_color(text, |mut color| {
color.0 = if enabled { Color::BLACK } else { Color::WHITE };
});
}
}
}
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
fn set_camera_viewports(
windows: Query<&Window>,
mut resize_events: EventReader<WindowResized>,
mut query: Query<(&CameraPosition, &mut Camera)>,
) {
// We need to dynamically resize the camera's viewports whenever the window size changes
// so then each camera always takes up half the screen.
// A resize_event is sent when the window is first created, allowing us to reuse this system for initial setup.
for resize_event in resize_events.read() {
let window = windows.get(resize_event.window).unwrap();
let size = window.physical_size() / 2;
for (camera_position, mut camera) in &mut query {
camera.viewport = Some(Viewport {
physical_position: camera_position.pos * size,
physical_size: size,
..default()
});
}
}
}
Sourcepub fn get_many<const N: usize>(
&self,
entities: [Entity; N],
) -> Result<[<<D as QueryData>::ReadOnly as WorldQuery>::Item<'_>; N], QueryEntityError<'_>>
pub fn get_many<const N: usize>( &self, entities: [Entity; N], ) -> Result<[<<D as QueryData>::ReadOnly as WorldQuery>::Item<'_>; N], QueryEntityError<'_>>
Returns the read-only query items for the given array of Entity
.
The returned query items are in the same order as the input.
In case of a nonexisting entity or mismatched component, a QueryEntityError
is returned instead.
The elements of the array do not need to be unique, unlike get_many_mut
.
§See also
get_many_mut
to get mutable query items.many
for the panicking version.
Sourcepub fn many<const N: usize>(
&self,
entities: [Entity; N],
) -> [<<D as QueryData>::ReadOnly as WorldQuery>::Item<'_>; N]
pub fn many<const N: usize>( &self, entities: [Entity; N], ) -> [<<D as QueryData>::ReadOnly as WorldQuery>::Item<'_>; N]
Returns the read-only query items for the given array of Entity
.
§Panics
This method panics if there is a query mismatch or a non-existing entity.
§Examples
use bevy_ecs::prelude::*;
#[derive(Component)]
struct Targets([Entity; 3]);
#[derive(Component)]
struct Position{
x: i8,
y: i8
};
impl Position {
fn distance(&self, other: &Position) -> i8 {
// Manhattan distance is way easier to compute!
(self.x - other.x).abs() + (self.y - other.y).abs()
}
}
fn check_all_targets_in_range(targeting_query: Query<(Entity, &Targets, &Position)>, targets_query: Query<&Position>){
for (targeting_entity, targets, origin) in &targeting_query {
// We can use "destructuring" to unpack the results nicely
let [target_1, target_2, target_3] = targets_query.many(targets.0);
assert!(target_1.distance(origin) <= 5);
assert!(target_2.distance(origin) <= 5);
assert!(target_3.distance(origin) <= 5);
}
}
§See also
get_many
for the non-panicking version.
Sourcepub fn get_mut(
&mut self,
entity: Entity,
) -> Result<<D as WorldQuery>::Item<'_>, QueryEntityError<'_>>
pub fn get_mut( &mut self, entity: Entity, ) -> Result<<D as WorldQuery>::Item<'_>, QueryEntityError<'_>>
Returns the query item for the given Entity
.
In case of a nonexisting entity or mismatched component, a QueryEntityError
is returned instead.
This is always guaranteed to run in O(1)
time.
§Example
Here, get_mut
is used to retrieve the exact query item of the entity specified by the PoisonedCharacter
resource.
fn poison_system(mut query: Query<&mut Health>, poisoned: Res<PoisonedCharacter>) {
if let Ok(mut health) = query.get_mut(poisoned.character_id) {
health.0 -= 1;
}
}
§See also
get
to get a read-only query item.
Examples found in repository?
More examples
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
fn update_material_on<E>(
new_material: Handle<StandardMaterial>,
) -> impl Fn(Trigger<E>, Query<&mut MeshMaterial3d<StandardMaterial>>) {
// An observer closure that captures `new_material`. We do this to avoid needing to write four
// versions of this observer, each triggered by a different event and with a different hardcoded
// material. Instead, the event type is a generic, and the material is passed in.
move |trigger, mut query| {
if let Ok(mut material) = query.get_mut(trigger.entity()) {
material.0 = new_material.clone();
}
}
}
/// A system that draws hit indicators for every pointer.
fn draw_mesh_intersections(pointers: Query<&PointerInteraction>, mut gizmos: Gizmos) {
for (point, normal) in pointers
.iter()
.filter_map(|interaction| interaction.get_nearest_hit())
.filter_map(|(_entity, hit)| hit.position.zip(hit.normal))
{
gizmos.sphere(point, 0.05, RED_500);
gizmos.arrow(point, point + normal.normalize() * 0.5, PINK_100);
}
}
/// A system that rotates all shapes.
fn rotate(mut query: Query<&mut Transform, With<Shape>>, time: Res<Time>) {
for mut transform in &mut query {
transform.rotate_y(time.delta_secs() / 2.);
}
}
/// An observer to rotate an entity when it is dragged
fn rotate_on_drag(drag: Trigger<Pointer<Drag>>, mut transforms: Query<&mut Transform>) {
let mut transform = transforms.get_mut(drag.entity()).unwrap();
transform.rotate_y(drag.delta.x * 0.02);
transform.rotate_x(drag.delta.y * 0.02);
}
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
fn take_damage(
trigger: Trigger<Attack>,
mut hp: Query<(&mut HitPoints, &Name)>,
mut commands: Commands,
mut app_exit: EventWriter<AppExit>,
) {
let attack = trigger.event();
let (mut hp, name) = hp.get_mut(trigger.entity()).unwrap();
**hp = hp.saturating_sub(attack.damage);
if **hp > 0 {
info!("{} has {:.1} HP", name, hp.0);
} else {
warn!("💀 {} has died a gruesome death", name);
commands.entity(trigger.entity()).despawn_recursive();
app_exit.send(AppExit::Success);
}
info!("(propagation reached root)\n");
}
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
fn move_scene_entities(
time: Res<Time>,
moved_scene: Query<Entity, With<MovedScene>>,
children: Query<&Children>,
mut transforms: Query<&mut Transform>,
) {
for moved_scene_entity in &moved_scene {
let mut offset = 0.;
for entity in children.iter_descendants(moved_scene_entity) {
if let Ok(mut transform) = transforms.get_mut(entity) {
transform.translation = Vec3::new(
offset * ops::sin(time.elapsed_secs()) / 20.,
0.,
ops::cos(time.elapsed_secs()) / 20.,
);
offset += 0.5;
}
}
}
}
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301
fn pause_animation_frame(
trigger: Trigger<SceneInstanceReady>,
children: Query<&Children>,
mut commands: Commands,
animation: Res<Animation>,
mut players: Query<(Entity, &mut AnimationPlayer)>,
) {
let entity = children.get(trigger.entity()).unwrap()[0];
let entity = children.get(entity).unwrap()[0];
let (entity, mut player) = players.get_mut(entity).unwrap();
let mut transitions = AnimationTransitions::new();
transitions
.play(&mut player, animation.animation, Duration::ZERO)
.seek_to(0.5)
.pause();
commands
.entity(entity)
.insert(AnimationGraphHandle(animation.graph.clone()))
.insert(transitions);
}
- examples/ui/ui_texture_slice.rs
- examples/ui/ghost_nodes.rs
- examples/3d/split_screen.rs
- examples/ui/ui_texture_atlas_slice.rs
- examples/ui/display_and_visibility.rs
- examples/ui/ui.rs
- examples/ui/button.rs
- examples/ui/scroll.rs
- examples/animation/gltf_skinned_mesh.rs
- examples/3d/motion_blur.rs
- examples/games/contributors.rs
- examples/ecs/hierarchy.rs
- examples/picking/simple_picking.rs
- examples/games/alien_cake_addict.rs
- examples/animation/easing_functions.rs
- examples/ui/size_constraints.rs
Sourcepub fn get_many_mut<const N: usize>(
&mut self,
entities: [Entity; N],
) -> Result<[<D as WorldQuery>::Item<'_>; N], QueryEntityError<'_>>
pub fn get_many_mut<const N: usize>( &mut self, entities: [Entity; N], ) -> Result<[<D as WorldQuery>::Item<'_>; N], QueryEntityError<'_>>
Returns the query items for the given array of Entity
.
The returned query items are in the same order as the input.
In case of a nonexisting entity, duplicate entities or mismatched component, a QueryEntityError
is returned instead.
§See also
Sourcepub fn many_mut<const N: usize>(
&mut self,
entities: [Entity; N],
) -> [<D as WorldQuery>::Item<'_>; N]
pub fn many_mut<const N: usize>( &mut self, entities: [Entity; N], ) -> [<D as WorldQuery>::Item<'_>; N]
Returns the query items for the given array of Entity
.
§Panics
This method panics if there is a query mismatch, a non-existing entity, or the same Entity
is included more than once in the array.
§Examples
use bevy_ecs::prelude::*;
#[derive(Component)]
struct Spring{
connected_entities: [Entity; 2],
strength: f32,
}
#[derive(Component)]
struct Position {
x: f32,
y: f32,
}
#[derive(Component)]
struct Force {
x: f32,
y: f32,
}
fn spring_forces(spring_query: Query<&Spring>, mut mass_query: Query<(&Position, &mut Force)>){
for spring in &spring_query {
// We can use "destructuring" to unpack our query items nicely
let [(position_1, mut force_1), (position_2, mut force_2)] = mass_query.many_mut(spring.connected_entities);
force_1.x += spring.strength * (position_1.x - position_2.x);
force_1.y += spring.strength * (position_1.y - position_2.y);
// Silence borrow-checker: I have split your mutable borrow!
force_2.x += spring.strength * (position_2.x - position_1.x);
force_2.y += spring.strength * (position_2.y - position_1.y);
}
}
§See also
get_many_mut
for the non panicking version.many
to get read-only query items.
Sourcepub unsafe fn get_unchecked(
&self,
entity: Entity,
) -> Result<<D as WorldQuery>::Item<'_>, QueryEntityError<'_>>
pub unsafe fn get_unchecked( &self, entity: Entity, ) -> Result<<D as WorldQuery>::Item<'_>, QueryEntityError<'_>>
Returns the query item for the given Entity
.
In case of a nonexisting entity or mismatched component, a QueryEntityError
is returned instead.
This is always guaranteed to run in O(1)
time.
§Safety
This function makes it possible to violate Rust’s aliasing guarantees. You must make sure this call does not result in multiple mutable references to the same component.
§See also
get_mut
for the safe version.
Sourcepub fn single(&self) -> <<D as QueryData>::ReadOnly as WorldQuery>::Item<'_>
pub fn single(&self) -> <<D as QueryData>::ReadOnly as WorldQuery>::Item<'_>
Returns a single read-only query item when there is exactly one entity matching the query.
§Panics
This method panics if the number of query items is not exactly one.
§Example
fn player_system(query: Query<&Position, With<Player>>) {
let player_position = query.single();
// do something with player_position
}
§See also
get_single
for the non-panicking version.single_mut
to get the mutable query item.
Examples found in repository?
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
fn handle_input(
input: Res<ButtonInput<KeyCode>>,
mut action: ResMut<LeftClickAction>,
mut dir: ResMut<ResizeDir>,
example_text: Query<Entity, With<Text>>,
mut writer: TextUiWriter,
) {
use LeftClickAction::*;
if input.just_pressed(KeyCode::KeyA) {
*action = match *action {
Move => Resize,
Resize => Nothing,
Nothing => Move,
};
*writer.text(example_text.single(), 4) = format!("{:?}", *action);
}
if input.just_pressed(KeyCode::KeyS) {
dir.0 = dir
.0
.checked_sub(1)
.unwrap_or(DIRECTIONS.len().saturating_sub(1));
*writer.text(example_text.single(), 7) = format!("{:?}", DIRECTIONS[dir.0]);
}
if input.just_pressed(KeyCode::KeyD) {
dir.0 = (dir.0 + 1) % DIRECTIONS.len();
*writer.text(example_text.single(), 7) = format!("{:?}", DIRECTIONS[dir.0]);
}
}
More examples
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 82 83 84 85 86
fn setup(
mut commands: Commands,
mut meshes: ResMut<Assets<Mesh>>,
mut materials: ResMut<Assets<StandardMaterial>>,
window: Query<&Window>,
) {
// circular 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)),
));
// cube
commands.spawn((
Mesh3d(meshes.add(Cuboid::new(1.0, 1.0, 1.0))),
MeshMaterial3d(materials.add(Color::WHITE)),
Transform::from_xyz(0.0, 0.5, 0.0),
));
// lights
for i in 0..NUM_LIGHTS {
let angle = (i as f32) / (NUM_LIGHTS as f32) * PI * 2.0;
commands.spawn((
PointLight {
color: Color::hsv(angle.to_degrees(), 1.0, 1.0),
intensity: 2_000_000.0 / NUM_LIGHTS as f32,
shadows_enabled: true,
..default()
},
Transform::from_xyz(sin(angle) * 4.0, 2.0, cos(angle) * 4.0),
));
}
// cameras
let window = window.single();
let width = window.resolution.width() / CAMERA_COLS as f32 * window.resolution.scale_factor();
let height = window.resolution.height() / CAMERA_ROWS as f32 * window.resolution.scale_factor();
let mut i = 0;
for y in 0..CAMERA_COLS {
for x in 0..CAMERA_ROWS {
let angle = i as f32 / (CAMERA_ROWS * CAMERA_COLS) as f32 * PI * 2.0;
commands.spawn((
Camera3d::default(),
Camera {
viewport: Some(Viewport {
physical_position: UVec2::new(
(x as f32 * width) as u32,
(y as f32 * height) as u32,
),
physical_size: UVec2::new(width as u32, height as u32),
..default()
}),
order: i,
..default()
},
Transform::from_xyz(sin(angle) * 4.0, 2.5, cos(angle) * 4.0)
.looking_at(Vec3::ZERO, Vec3::Y),
));
i += 1;
}
}
}
Sourcepub fn get_single(
&self,
) -> Result<<<D as QueryData>::ReadOnly as WorldQuery>::Item<'_>, QuerySingleError>
pub fn get_single( &self, ) -> Result<<<D as QueryData>::ReadOnly as WorldQuery>::Item<'_>, QuerySingleError>
Returns a single read-only query item when there is exactly one entity matching the query.
If the number of query items is not exactly one, a QuerySingleError
is returned instead.
§Example
fn player_scoring_system(query: Query<&PlayerScore>) {
match query.get_single() {
Ok(PlayerScore(score)) => {
println!("Score: {}", score);
}
Err(QuerySingleError::NoEntities(_)) => {
println!("Error: There is no player!");
}
Err(QuerySingleError::MultipleEntities(_)) => {
println!("Error: There is more than one player!");
}
}
}
§See also
get_single_mut
to get the mutable query item.single
for the panicking version.
Examples found in repository?
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
fn update_speed(music_controller: Query<&AudioSink, With<MyMusic>>, time: Res<Time>) {
if let Ok(sink) = music_controller.get_single() {
sink.set_speed((ops::sin(time.elapsed_secs() / 5.0) + 1.0).max(0.1));
}
}
fn pause(
keyboard_input: Res<ButtonInput<KeyCode>>,
music_controller: Query<&AudioSink, With<MyMusic>>,
) {
if keyboard_input.just_pressed(KeyCode::Space) {
if let Ok(sink) = music_controller.get_single() {
sink.toggle();
}
}
}
fn volume(
keyboard_input: Res<ButtonInput<KeyCode>>,
music_controller: Query<&AudioSink, With<MyMusic>>,
) {
if let Ok(sink) = music_controller.get_single() {
if keyboard_input.just_pressed(KeyCode::Equal) {
sink.set_volume(sink.volume() + 0.1);
} else if keyboard_input.just_pressed(KeyCode::Minus) {
sink.set_volume(sink.volume() - 0.1);
}
}
}
More examples
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));
}
_ => {}
}
}
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
fn draw_cursor(
camera_query: Single<(&Camera, &GlobalTransform)>,
windows: Query<&Window>,
mut gizmos: Gizmos,
) {
let (camera, camera_transform) = *camera_query;
let Ok(window) = windows.get_single() else {
return;
};
let Some(cursor_position) = window.cursor_position() else {
return;
};
// Calculate a world position based on the cursor's position.
let Ok(point) = camera.viewport_to_world_2d(camera_transform, cursor_position) else {
return;
};
gizmos.circle_2d(point, 10., WHITE);
}
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();
}
}
}
}
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
fn update_camera(
mut camera: Query<&mut Transform, (With<Camera2d>, Without<Player>)>,
player: Query<&Transform, (With<Player>, Without<Camera2d>)>,
time: Res<Time>,
) {
let Ok(mut camera) = camera.get_single_mut() else {
return;
};
let Ok(player) = player.get_single() else {
return;
};
let Vec3 { x, y, .. } = player.translation;
let direction = Vec3::new(x, y, camera.translation.z);
// Applies a smooth effect to camera movement using stable interpolation
// between the camera position and the player position on the x and y axes.
camera
.translation
.smooth_nudge(&direction, CAMERA_DECAY_RATE, time.delta_secs());
}
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145
fn alter_asset(mut images: ResMut<Assets<Image>>, left_bird: Query<&Sprite, With<Left>>) {
// It's convenient to retrieve the asset handle stored with the bird on the left. However,
// we could just as easily have retained this in a resource or a dedicated component.
let Ok(sprite) = left_bird.get_single() else {
return;
};
// Obtain a mutable reference to the Image asset.
let Some(image) = images.get_mut(&sprite.image) else {
return;
};
for pixel in &mut image.data {
// Directly modify the asset data, which will affect all users of this asset. By
// contrast, mutating the handle (as we did above) affects only one copy. In this case,
// we'll just invert the colors, by way of demonstration. Notice that both uses of the
// asset show the change, not just the one on the left.
*pixel = 255 - *pixel;
}
}
Sourcepub fn single_mut(&mut self) -> <D as WorldQuery>::Item<'_>
pub fn single_mut(&mut self) -> <D as WorldQuery>::Item<'_>
Returns a single query item when there is exactly one entity matching the query.
§Panics
This method panics if the number of query items is not exactly one.
§Example
fn regenerate_player_health_system(mut query: Query<&mut Health, With<Player>>) {
let mut health = query.single_mut();
health.0 += 1;
}
§See also
get_single_mut
for the non-panicking version.single
to get the read-only query item.
Sourcepub fn get_single_mut(
&mut self,
) -> Result<<D as WorldQuery>::Item<'_>, QuerySingleError>
pub fn get_single_mut( &mut self, ) -> Result<<D as WorldQuery>::Item<'_>, QuerySingleError>
Returns a single query item when there is exactly one entity matching the query.
If the number of query items is not exactly one, a QuerySingleError
is returned instead.
§Example
fn regenerate_player_health_system(mut query: Query<&mut Health, With<Player>>) {
let mut health = query.get_single_mut().expect("Error: Could not find a single player.");
health.0 += 1;
}
§See also
get_single
to get the read-only query item.single_mut
for the panicking version.
Examples found in repository?
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
fn get_async_loading_state(
state: Res<AsyncLoadingState>,
mut next_loading_state: ResMut<NextState<LoadingState>>,
mut text: Query<&mut Text, With<LoadingText>>,
) {
// Load the value written by the `Future`.
let is_loaded = state.0.load(Ordering::Acquire);
// If loaded, change the state.
if is_loaded {
next_loading_state.set(LoadingState::Loaded);
if let Ok(mut text) = text.get_single_mut() {
"Loaded!".clone_into(&mut **text);
}
}
}
More examples
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 128 129 130 131 132 133 134 135
fn update_camera(
mut camera: Query<&mut Transform, (With<Camera2d>, Without<Player>)>,
player: Query<&Transform, (With<Player>, Without<Camera2d>)>,
time: Res<Time>,
) {
let Ok(mut camera) = camera.get_single_mut() else {
return;
};
let Ok(player) = player.get_single() else {
return;
};
let Vec3 { x, y, .. } = player.translation;
let direction = Vec3::new(x, y, camera.translation.z);
// Applies a smooth effect to camera movement using stable interpolation
// between the camera position and the player position on the x and y axes.
camera
.translation
.smooth_nudge(&direction, CAMERA_DECAY_RATE, time.delta_secs());
}
/// Update the player position with keyboard inputs.
/// Note that the approach used here is for demonstration purposes only,
/// as the point of this example is to showcase the camera tracking feature.
///
/// A more robust solution for player movement can be found in `examples/movement/physics_in_fixed_timestep.rs`.
fn move_player(
mut player: Query<&mut Transform, With<Player>>,
time: Res<Time>,
kb_input: Res<ButtonInput<KeyCode>>,
) {
let Ok(mut player) = player.get_single_mut() else {
return;
};
let mut direction = Vec2::ZERO;
if kb_input.pressed(KeyCode::KeyW) {
direction.y += 1.;
}
if kb_input.pressed(KeyCode::KeyS) {
direction.y -= 1.;
}
if kb_input.pressed(KeyCode::KeyA) {
direction.x -= 1.;
}
if kb_input.pressed(KeyCode::KeyD) {
direction.x += 1.;
}
// Progressively update the player's position over time. Normalize the
// direction vector to prevent it from exceeding a magnitude of 1 when
// moving diagonally.
let move_delta = direction.normalize_or_zero() * PLAYER_SPEED * time.delta_secs();
player.translation += move_delta.extend(0.);
}
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
fn alter_handle(
asset_server: Res<AssetServer>,
mut right_bird: Query<(&mut Bird, &mut Sprite), Without<Left>>,
) {
// Image handles, like other parts of the ECS, can be queried as mutable and modified at
// runtime. We only spawned one bird without the `Left` marker component.
let Ok((mut bird, mut sprite)) = right_bird.get_single_mut() else {
return;
};
// Switch to a new Bird variant
bird.set_next_variant();
// Modify the handle associated with the Bird on the right side. Note that we will only
// have to load the same path from storage media once: repeated attempts will re-use the
// asset.
sprite.image = asset_server.load(bird.get_texture_path());
}
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 alter_handle(
asset_server: Res<AssetServer>,
mut right_shape: Query<(&mut Mesh3d, &mut Shape), Without<Left>>,
) {
// Mesh handles, like other parts of the ECS, can be queried as mutable and modified at
// runtime. We only spawned one shape without the `Left` marker component.
let Ok((mut mesh, mut shape)) = right_shape.get_single_mut() else {
return;
};
// Switch to a new Shape variant
shape.set_next_variant();
// Modify the handle associated with the Shape on the right side. Note that we will only
// have to load the same path from storage media once: repeated attempts will re-use the
// asset.
mesh.0 = asset_server.load(
GltfAssetLabel::Primitive {
mesh: 0,
primitive: 0,
}
.from_asset(shape.get_model_path()),
);
}
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
fn screen_shake(
time: Res<Time>,
mut screen_shake: ResMut<ScreenShake>,
mut query: Query<(&mut Camera, &mut Transform)>,
) {
let mut rng = ChaCha8Rng::from_entropy();
let shake = screen_shake.trauma * screen_shake.trauma;
let angle = (screen_shake.max_angle * shake).to_radians() * rng.gen_range(-1.0..1.0);
let offset_x = screen_shake.max_offset * shake * rng.gen_range(-1.0..1.0);
let offset_y = screen_shake.max_offset * shake * rng.gen_range(-1.0..1.0);
if shake > 0.0 {
for (mut camera, mut transform) in query.iter_mut() {
// Position
let sub_view = camera.sub_camera_view.as_mut().unwrap();
let target = sub_view.offset
+ Vec2 {
x: offset_x,
y: offset_y,
};
sub_view
.offset
.smooth_nudge(&target, CAMERA_DECAY_RATE, time.delta_secs());
// Rotation
let rotation = Quat::from_rotation_z(angle);
transform.rotation = transform
.rotation
.interpolate_stable(&(transform.rotation.mul_quat(rotation)), CAMERA_DECAY_RATE);
}
} else {
// return camera to the latest position of player (it's fixed in this example case)
if let Ok((mut camera, mut transform)) = query.get_single_mut() {
let sub_view = camera.sub_camera_view.as_mut().unwrap();
let target = screen_shake.latest_position.unwrap();
sub_view
.offset
.smooth_nudge(&target, 1.0, time.delta_secs());
transform.rotation = transform.rotation.interpolate_stable(&Quat::IDENTITY, 0.1);
}
}
// Decay the trauma over time
screen_shake.trauma -= TRAUMA_DECAY_SPEED * time.delta_secs();
screen_shake.trauma = screen_shake.trauma.clamp(0.0, 1.0);
}
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
fn move_player(
accumulated_mouse_motion: Res<AccumulatedMouseMotion>,
mut player: Query<(&mut Transform, &CameraSensitivity), With<Player>>,
) {
let Ok((mut transform, camera_sensitivity)) = player.get_single_mut() else {
return;
};
let delta = accumulated_mouse_motion.delta;
if delta != Vec2::ZERO {
// Note that we are not multiplying by delta_time here.
// The reason is that for mouse movement, we already get the full movement that happened since the last frame.
// This means that if we multiply by delta_time, we will get a smaller rotation than intended by the user.
// This situation is reversed when reading e.g. analog input from a gamepad however, where the same rules
// as for keyboard input apply. Such an input should be multiplied by delta_time to get the intended rotation
// independent of the framerate.
let delta_yaw = -delta.x * camera_sensitivity.x;
let delta_pitch = -delta.y * camera_sensitivity.y;
let (yaw, pitch, roll) = transform.rotation.to_euler(EulerRot::YXZ);
let yaw = yaw + delta_yaw;
// If the pitch was ±¹⁄₂ π, the camera would look straight up or down.
// When the user wants to move the camera back to the horizon, which way should the camera face?
// The camera has no way of knowing what direction was "forward" before landing in that extreme position,
// so the direction picked will for all intents and purposes be arbitrary.
// Another issue is that for mathematical reasons, the yaw will effectively be flipped when the pitch is at the extremes.
// To not run into these issues, we clamp the pitch to a safe range.
const PITCH_LIMIT: f32 = FRAC_PI_2 - 0.01;
let pitch = (pitch + delta_pitch).clamp(-PITCH_LIMIT, PITCH_LIMIT);
transform.rotation = Quat::from_euler(EulerRot::YXZ, yaw, pitch, roll);
}
}
fn change_fov(
input: Res<ButtonInput<KeyCode>>,
mut world_model_projection: Query<&mut Projection, With<WorldModelCamera>>,
) {
let Ok(mut projection) = world_model_projection.get_single_mut() else {
return;
};
let Projection::Perspective(ref mut perspective) = projection.as_mut() else {
unreachable!(
"The `Projection` component was explicitly built with `Projection::Perspective`"
);
};
if input.pressed(KeyCode::ArrowUp) {
perspective.fov -= 1.0_f32.to_radians();
perspective.fov = perspective.fov.max(20.0_f32.to_radians());
}
if input.pressed(KeyCode::ArrowDown) {
perspective.fov += 1.0_f32.to_radians();
perspective.fov = perspective.fov.min(160.0_f32.to_radians());
}
}
Sourcepub fn is_empty(&self) -> bool
pub fn is_empty(&self) -> bool
Returns true
if there are no query items.
This is equivalent to self.iter().next().is_none()
, and thus the worst case runtime will be O(n)
where n
is the number of potential matches. This can be notably expensive for queries that rely
on non-archetypal filters such as Added
or Changed
which must individually check each query
result for a match.
§Example
Here, the score is increased only if an entity with a Player
component is present in the world:
fn update_score_system(query: Query<(), With<Player>>, mut score: ResMut<Score>) {
if !query.is_empty() {
score.0 += 1;
}
}
Examples found in repository?
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 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);
}
}
}
}
}
Sourcepub fn transmute_lens<NewD>(&mut self) -> QueryLens<'_, NewD>where
NewD: QueryData,
pub fn transmute_lens<NewD>(&mut self) -> QueryLens<'_, NewD>where
NewD: QueryData,
Returns a QueryLens
that can be used to get a query with a more general fetch.
For example, this can transform a Query<(&A, &mut B)>
to a Query<&B>
.
This can be useful for passing the query to another function. Note that since
filter terms are dropped, non-archetypal filters like Added
and
Changed
will not be respected. To maintain or change filter
terms see Self::transmute_lens_filtered
§Panics
This will panic if NewD
is not a subset of the original fetch Q
§Example
fn reusable_function(lens: &mut QueryLens<&A>) {
assert_eq!(lens.query().single().0, 10);
}
// We can use the function in a system that takes the exact query.
fn system_1(mut query: Query<&A>) {
reusable_function(&mut query.as_query_lens());
}
// We can also use it with a query that does not match exactly
// by transmuting it.
fn system_2(mut query: Query<(&mut A, &B)>) {
let mut lens = query.transmute_lens::<&A>();
reusable_function(&mut lens);
}
§Allowed Transmutes
Besides removing parameters from the query, you can also make limited changes to the types of parameters.
- Can always add/remove
Entity
- Can always add/remove
EntityLocation
- Can always add/remove
&Archetype
Ref<T>
<->&T
&mut T
->&T
&mut T
->Ref<T>
EntityMut
->EntityRef
Sourcepub fn transmute_lens_filtered<NewD, NewF>(
&mut self,
) -> QueryLens<'_, NewD, NewF>where
NewD: QueryData,
NewF: QueryFilter,
pub fn transmute_lens_filtered<NewD, NewF>(
&mut self,
) -> QueryLens<'_, NewD, NewF>where
NewD: QueryData,
NewF: QueryFilter,
Equivalent to Self::transmute_lens
but also includes a QueryFilter
type.
Note that the lens will iterate the same tables and archetypes as the original query. This means that
additional archetypal query terms like With
and Without
will not necessarily be respected and non-archetypal terms like Added
and
Changed
will only be respected if they are in the type signature.
Sourcepub fn as_query_lens(&mut self) -> QueryLens<'_, D>
pub fn as_query_lens(&mut self) -> QueryLens<'_, D>
Gets a QueryLens
with the same accesses as the existing query
Sourcepub fn join<OtherD, NewD>(
&mut self,
other: &mut Query<'_, '_, OtherD>,
) -> QueryLens<'_, NewD>
pub fn join<OtherD, NewD>( &mut self, other: &mut Query<'_, '_, OtherD>, ) -> QueryLens<'_, NewD>
Returns a QueryLens
that can be used to get a query with the combined fetch.
For example, this can take a Query<&A>
and a Query<&B>
and return a Query<(&A, &B)>
.
The returned query will only return items with both A
and B
. Note that since filters
are dropped, non-archetypal filters like Added
and Changed
will not be respected.
To maintain or change filter terms see Self::join_filtered
.
§Example
fn system(
mut transforms: Query<&Transform>,
mut players: Query<&Player>,
mut enemies: Query<&Enemy>
) {
let mut players_transforms: QueryLens<(&Transform, &Player)> = transforms.join(&mut players);
for (transform, player) in &players_transforms.query() {
// do something with a and b
}
let mut enemies_transforms: QueryLens<(&Transform, &Enemy)> = transforms.join(&mut enemies);
for (transform, enemy) in &enemies_transforms.query() {
// do something with a and b
}
}
§Panics
This will panic if NewD
is not a subset of the union of the original fetch Q
and OtherD
.
§Allowed Transmutes
Like transmute_lens
the query terms can be changed with some restrictions.
See Self::transmute_lens
for more details.
Sourcepub fn join_filtered<OtherD, OtherF, NewD, NewF>(
&mut self,
other: &mut Query<'_, '_, OtherD, OtherF>,
) -> QueryLens<'_, NewD, NewF>
pub fn join_filtered<OtherD, OtherF, NewD, NewF>( &mut self, other: &mut Query<'_, '_, OtherD, OtherF>, ) -> QueryLens<'_, NewD, NewF>
Equivalent to Self::join
but also includes a QueryFilter
type.
Note that the lens with iterate a subset of the original queries’ tables
and archetypes. This means that additional archetypal query terms like
With
and Without
will not necessarily be respected and non-archetypal
terms like Added
and Changed
will only be respected if they are in
the type signature.
Source§impl<'w, 's, D, F> Query<'w, 's, D, F>where
D: ReadOnlyQueryData,
F: QueryFilter,
impl<'w, 's, D, F> Query<'w, 's, D, F>where
D: ReadOnlyQueryData,
F: QueryFilter,
Sourcepub fn get_inner(
&self,
entity: Entity,
) -> Result<<<D as QueryData>::ReadOnly as WorldQuery>::Item<'w>, QueryEntityError<'_>>
pub fn get_inner( &self, entity: Entity, ) -> Result<<<D as QueryData>::ReadOnly as WorldQuery>::Item<'w>, QueryEntityError<'_>>
Returns the query item for the given Entity
, with the actual “inner” world lifetime.
In case of a nonexisting entity or mismatched component, a QueryEntityError
is
returned instead.
This can only return immutable data (mutable data will be cast to an immutable form).
See get_mut
for queries that contain at least one mutable component.
§Example
Here, get
is used to retrieve the exact query item of the entity specified by the
SelectedCharacter
resource.
fn print_selected_character_name_system(
query: Query<&Character>,
selection: Res<SelectedCharacter>
)
{
if let Ok(selected_character) = query.get(selection.entity) {
println!("{}", selected_character.name);
}
}
Sourcepub fn iter_inner(&self) -> QueryIter<'w, 's, <D as QueryData>::ReadOnly, F> ⓘ
pub fn iter_inner(&self) -> QueryIter<'w, 's, <D as QueryData>::ReadOnly, F> ⓘ
Returns an Iterator
over the query items, with the actual “inner” world lifetime.
This can only return immutable data (mutable data will be cast to an immutable form).
See Self::iter_mut
for queries that contain at least one mutable component.
§Example
Here, the report_names_system
iterates over the Player
component of every entity
that contains it:
fn report_names_system(query: Query<&Player>) {
for player in &query {
println!("Say hello to {}!", player.name);
}
}
Trait Implementations§
Source§impl<'w, 'q, Q, F> From<&'q mut Query<'w, '_, Q, F>> for QueryLens<'q, Q, F>where
Q: QueryData,
F: QueryFilter,
impl<'w, 'q, Q, F> From<&'q mut Query<'w, '_, Q, F>> for QueryLens<'q, Q, F>where
Q: QueryData,
F: QueryFilter,
Source§impl<'w, 's, Q, F> From<&'s mut QueryLens<'w, Q, F>> for Query<'w, 's, Q, F>where
Q: QueryData,
F: QueryFilter,
impl<'w, 's, Q, F> From<&'s mut QueryLens<'w, Q, F>> for Query<'w, 's, Q, F>where
Q: QueryData,
F: QueryFilter,
Source§impl<'w, 's, D, F> HierarchyQueryExt<'w, 's, D, F> for Query<'w, 's, D, F>where
D: QueryData,
F: QueryFilter,
impl<'w, 's, D, F> HierarchyQueryExt<'w, 's, D, F> for Query<'w, 's, D, F>where
D: QueryData,
F: QueryFilter,
Source§fn parent(&'w self, entity: Entity) -> Option<Entity>
fn parent(&'w self, entity: Entity) -> Option<Entity>
Entity
of the given entity
, if any.Source§fn root_ancestor(&'w self, entity: Entity) -> Entity
fn root_ancestor(&'w self, entity: Entity) -> Entity
entity
. Read moreSource§fn iter_descendants(&'w self, entity: Entity) -> DescendantIter<'w, 's, D, F> ⓘ
fn iter_descendants(&'w self, entity: Entity) -> DescendantIter<'w, 's, D, F> ⓘ
Source§fn iter_descendants_depth_first(
&'w self,
entity: Entity,
) -> DescendantDepthFirstIter<'w, 's, D, F> ⓘ
fn iter_descendants_depth_first( &'w self, entity: Entity, ) -> DescendantDepthFirstIter<'w, 's, D, F> ⓘ
Source§fn iter_ancestors(&'w self, entity: Entity) -> AncestorIter<'w, 's, D, F> ⓘ
fn iter_ancestors(&'w self, entity: Entity) -> AncestorIter<'w, 's, D, F> ⓘ
Source§impl<'w, 's, D, F> IntoIterator for &'w Query<'_, 's, D, F>where
D: QueryData,
F: QueryFilter,
impl<'w, 's, D, F> IntoIterator for &'w Query<'_, 's, D, F>where
D: QueryData,
F: QueryFilter,
Source§impl<'w, 's, D, F> IntoIterator for &'w mut Query<'_, 's, D, F>where
D: QueryData,
F: QueryFilter,
impl<'w, 's, D, F> IntoIterator for &'w mut Query<'_, 's, D, F>where
D: QueryData,
F: QueryFilter,
Source§type Item = <D as WorldQuery>::Item<'w>
type Item = <D as WorldQuery>::Item<'w>
Source§impl<D, F> SystemParam for Query<'_, '_, D, F>where
D: QueryData + 'static,
F: QueryFilter + 'static,
impl<D, F> SystemParam for Query<'_, '_, D, F>where
D: QueryData + 'static,
F: QueryFilter + 'static,
Source§type State = QueryState<D, F>
type State = QueryState<D, F>
Source§type Item<'w, 's> = Query<'w, 's, D, F>
type Item<'w, 's> = Query<'w, 's, D, F>
Self
, instantiated with new lifetimes. Read moreSource§fn init_state(
world: &mut World,
system_meta: &mut SystemMeta,
) -> <Query<'_, '_, D, F> as SystemParam>::State
fn init_state( world: &mut World, system_meta: &mut SystemMeta, ) -> <Query<'_, '_, D, F> as SystemParam>::State
World
access used by this SystemParam
and creates a new instance of this param’s State
.Source§unsafe fn new_archetype(
state: &mut <Query<'_, '_, D, F> as SystemParam>::State,
archetype: &Archetype,
system_meta: &mut SystemMeta,
)
unsafe fn new_archetype( state: &mut <Query<'_, '_, D, F> as SystemParam>::State, archetype: &Archetype, system_meta: &mut SystemMeta, )
Archetype
, registers the components accessed by this SystemParam
(if applicable).a Read moreSource§unsafe fn get_param<'w, 's>(
state: &'s mut <Query<'_, '_, D, F> as SystemParam>::State,
system_meta: &SystemMeta,
world: UnsafeWorldCell<'w>,
change_tick: Tick,
) -> <Query<'_, '_, D, F> as SystemParam>::Item<'w, 's>
unsafe fn get_param<'w, 's>( state: &'s mut <Query<'_, '_, D, F> as SystemParam>::State, system_meta: &SystemMeta, world: UnsafeWorldCell<'w>, change_tick: Tick, ) -> <Query<'_, '_, D, F> as SystemParam>::Item<'w, 's>
SystemParamFunction
. Read moreSource§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
.Source§fn queue(
state: &mut Self::State,
system_meta: &SystemMeta,
world: DeferredWorld<'_>,
)
fn queue( state: &mut Self::State, system_meta: &SystemMeta, world: DeferredWorld<'_>, )
apply_deferred
.Source§unsafe fn validate_param(
_state: &Self::State,
_system_meta: &SystemMeta,
_world: UnsafeWorldCell<'_>,
) -> bool
unsafe fn validate_param( _state: &Self::State, _system_meta: &SystemMeta, _world: UnsafeWorldCell<'_>, ) -> bool
get_param
.
Built-in executors use this to prevent systems with invalid params from running.
For nested SystemParam
s validation will fail if any
delegated validation fails. Read moreSource§impl<'w, 's, D, F, T> SystemParamBuilder<Query<'w, 's, D, F>> for QueryParamBuilder<T>
impl<'w, 's, D, F, T> SystemParamBuilder<Query<'w, 's, D, F>> for QueryParamBuilder<T>
Source§fn build(
self,
world: &mut World,
system_meta: &mut SystemMeta,
) -> QueryState<D, F>
fn build( self, world: &mut World, system_meta: &mut SystemMeta, ) -> QueryState<D, F>
World
access used by this SystemParam
and creates a new instance of this param’s State
.Source§fn build_state(self, world: &mut World) -> SystemState<P>
fn build_state(self, world: &mut World) -> SystemState<P>
SystemState
from a SystemParamBuilder
.
To create a system, call SystemState::build_system
on the result.Source§impl<'w, 's, D, F> SystemParamBuilder<Query<'w, 's, D, F>> for QueryState<D, F>where
D: QueryData + 'static,
F: QueryFilter + 'static,
impl<'w, 's, D, F> SystemParamBuilder<Query<'w, 's, D, F>> for QueryState<D, F>where
D: QueryData + 'static,
F: QueryFilter + 'static,
Source§fn build(
self,
world: &mut World,
system_meta: &mut SystemMeta,
) -> QueryState<D, F>
fn build( self, world: &mut World, system_meta: &mut SystemMeta, ) -> QueryState<D, F>
World
access used by this SystemParam
and creates a new instance of this param’s State
.Source§fn build_state(self, world: &mut World) -> SystemState<P>
fn build_state(self, world: &mut World) -> SystemState<P>
SystemState
from a SystemParamBuilder
.
To create a system, call SystemState::build_system
on the result.impl<'w, 's, D, F> ReadOnlySystemParam for Query<'w, 's, D, F>where
D: ReadOnlyQueryData + 'static,
F: QueryFilter + 'static,
Auto Trait Implementations§
impl<'world, 'state, D, F> Freeze for Query<'world, 'state, D, F>
impl<'world, 'state, D, F = ()> !RefUnwindSafe for Query<'world, 'state, D, F>
impl<'world, 'state, D, F> Send for Query<'world, 'state, D, F>
impl<'world, 'state, D, F> Sync for Query<'world, 'state, D, F>
impl<'world, 'state, D, F> Unpin for Query<'world, 'state, D, F>
impl<'world, 'state, D, F = ()> !UnwindSafe for Query<'world, 'state, D, F>
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> MapEntities for Twhere
T: VisitEntitiesMut,
impl<T> MapEntities for Twhere
T: VisitEntitiesMut,
Source§fn map_entities<M>(&mut self, entity_mapper: &mut M)where
M: EntityMapper,
fn map_entities<M>(&mut self, entity_mapper: &mut M)where
M: EntityMapper,
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.