//! Demonstrates how contiguous queries work.1//!2//! Contiguous iteration enables getting slices of contiguously lying components (which lie in the same table), which for example3//! may be used for simd-operations, which may accelerate an algorithm.4//!5//! Contiguous iteration may be used for example via [`Query::contiguous_iter`], [`Query::contiguous_iter_mut`],6//! both of which return an option which is only [`None`] when the query doesn't support contiguous7//! iteration due to it not being dense (iteration happens on archetypes, not tables) or filters not being archetypal.8//!9//! For further documentation refer to:10//! - [`Query::contiguous_iter`]11//! - [`ContiguousQueryData`](`bevy::ecs::query::ContiguousQueryData`)12//! - [`ArchetypeFilter`](`bevy::ecs::query::ArchetypeFilter`)1314use bevy::prelude::*;1516#[derive(Component)]17/// When the value reaches 0.0 the entity dies18pub struct Health(pub f32);1920#[derive(Component)]21/// Each tick an entity will have it's health multiplied by the factor, which22/// for a big amount of entities can be accelerated using contiguous queries23pub struct HealthDecay(pub f32);2425fn apply_health_decay(mut query: Query<(&mut Health, &HealthDecay)>) {26// contiguous_iter_mut() would return None if query couldn't be iterated contiguously27for (mut health, decay) in query.contiguous_iter_mut().unwrap() {28// all data slices returned by component queries are the same size29assert!(health.len() == decay.len());30// we could also bypass change detection via bypass_change_detection() because we do not31// use it anyways.32for (health, decay) in health.iter_mut().zip(decay) {33health.0 *= decay.0;34}35}36}3738fn finish_off_first(mut commands: Commands, mut query: Query<(Entity, &mut Health)>) {39if let Some((entity, mut health)) = query.iter_mut().next() {40health.0 -= 1.0;41if health.0 <= 0.0 {42commands.entity(entity).despawn();43println!("Finishing off {entity:?}");44}45}46}4748fn main() {49App::new()50.add_plugins(DefaultPlugins)51.add_systems(Update, (apply_health_decay, finish_off_first).chain())52.add_systems(Startup, setup)53.run();54}5556fn setup(mut commands: Commands) {57let mut i = 0;58commands.spawn_batch(std::iter::from_fn(move || {59i += 1;60if i == 10_000 {61None62} else {63Some((Health(i as f32 * 5.0), HealthDecay(0.9)))64}65}));66}676869