pub mod command;
pub mod entity_command;
#[cfg(feature = "std")]
mod parallel_scope;
use bevy_ptr::move_as_ptr;
pub use command::Command;
pub use entity_command::EntityCommand;
#[cfg(feature = "std")]
pub use parallel_scope::*;
use alloc::boxed::Box;
use core::marker::PhantomData;
use crate::{
self as bevy_ecs,
bundle::{Bundle, InsertMode, NoBundleEffect},
change_detection::{MaybeLocation, Mut},
component::{Component, ComponentId, Mutable},
entity::{
Entities, Entity, EntityAllocator, EntityClonerBuilder, EntityNotSpawnedError,
InvalidEntityError, OptIn, OptOut,
},
error::{warn, BevyError, CommandWithEntity, ErrorContext, HandleError},
event::{EntityEvent, Event},
message::Message,
observer::Observer,
resource::Resource,
schedule::ScheduleLabel,
system::{
Deferred, IntoObserverSystem, IntoSystem, RegisteredSystem, SystemId, SystemInput,
SystemParamValidationError,
},
world::{
command_queue::RawCommandQueue, unsafe_world_cell::UnsafeWorldCell, CommandQueue,
EntityWorldMut, FromWorld, World,
},
};
pub struct Commands<'w, 's> {
queue: InternalQueue<'s>,
entities: &'w Entities,
allocator: &'w EntityAllocator,
}
unsafe impl Send for Commands<'_, '_> {}
unsafe impl Sync for Commands<'_, '_> {}
const _: () = {
type __StructFieldsAlias<'w, 's> = (
Deferred<'s, CommandQueue>,
&'w EntityAllocator,
&'w Entities,
);
#[doc(hidden)]
pub struct FetchState {
state: <__StructFieldsAlias<'static, 'static> as bevy_ecs::system::SystemParam>::State,
}
unsafe impl bevy_ecs::system::SystemParam for Commands<'_, '_> {
type State = FetchState;
type Item<'w, 's> = Commands<'w, 's>;
#[track_caller]
fn init_state(world: &mut World) -> Self::State {
FetchState {
state: <__StructFieldsAlias<'_, '_> as bevy_ecs::system::SystemParam>::init_state(
world,
),
}
}
fn init_access(
state: &Self::State,
system_meta: &mut bevy_ecs::system::SystemMeta,
component_access_set: &mut bevy_ecs::query::FilteredAccessSet,
world: &mut World,
) {
<__StructFieldsAlias<'_, '_> as bevy_ecs::system::SystemParam>::init_access(
&state.state,
system_meta,
component_access_set,
world,
);
}
fn apply(
state: &mut Self::State,
system_meta: &bevy_ecs::system::SystemMeta,
world: &mut World,
) {
<__StructFieldsAlias<'_, '_> as bevy_ecs::system::SystemParam>::apply(
&mut state.state,
system_meta,
world,
);
}
fn queue(
state: &mut Self::State,
system_meta: &bevy_ecs::system::SystemMeta,
world: bevy_ecs::world::DeferredWorld,
) {
<__StructFieldsAlias<'_, '_> as bevy_ecs::system::SystemParam>::queue(
&mut state.state,
system_meta,
world,
);
}
#[inline]
unsafe fn validate_param(
state: &mut Self::State,
system_meta: &bevy_ecs::system::SystemMeta,
world: UnsafeWorldCell,
) -> Result<(), SystemParamValidationError> {
unsafe {
<__StructFieldsAlias as bevy_ecs::system::SystemParam>::validate_param(
&mut state.state,
system_meta,
world,
)
}
}
#[inline]
#[track_caller]
unsafe fn get_param<'w, 's>(
state: &'s mut Self::State,
system_meta: &bevy_ecs::system::SystemMeta,
world: UnsafeWorldCell<'w>,
change_tick: bevy_ecs::change_detection::Tick,
) -> Self::Item<'w, 's> {
let params = unsafe {
<__StructFieldsAlias as bevy_ecs::system::SystemParam>::get_param(
&mut state.state,
system_meta,
world,
change_tick,
)
};
Commands {
queue: InternalQueue::CommandQueue(params.0),
allocator: params.1,
entities: params.2,
}
}
}
unsafe impl<'w, 's> bevy_ecs::system::ReadOnlySystemParam for Commands<'w, 's>
where
Deferred<'s, CommandQueue>: bevy_ecs::system::ReadOnlySystemParam,
&'w Entities: bevy_ecs::system::ReadOnlySystemParam,
{
}
};
enum InternalQueue<'s> {
CommandQueue(Deferred<'s, CommandQueue>),
RawCommandQueue(RawCommandQueue),
}
impl<'w, 's> Commands<'w, 's> {
pub fn new(queue: &'s mut CommandQueue, world: &'w World) -> Self {
Self::new_from_entities(queue, &world.allocator, &world.entities)
}
pub fn new_from_entities(
queue: &'s mut CommandQueue,
allocator: &'w EntityAllocator,
entities: &'w Entities,
) -> Self {
Self {
queue: InternalQueue::CommandQueue(Deferred(queue)),
allocator,
entities,
}
}
pub(crate) unsafe fn new_raw_from_entities(
queue: RawCommandQueue,
allocator: &'w EntityAllocator,
entities: &'w Entities,
) -> Self {
Self {
queue: InternalQueue::RawCommandQueue(queue),
allocator,
entities,
}
}
pub fn reborrow(&mut self) -> Commands<'w, '_> {
Commands {
queue: match &mut self.queue {
InternalQueue::CommandQueue(queue) => InternalQueue::CommandQueue(queue.reborrow()),
InternalQueue::RawCommandQueue(queue) => {
InternalQueue::RawCommandQueue(queue.clone())
}
},
allocator: self.allocator,
entities: self.entities,
}
}
pub fn append(&mut self, other: &mut CommandQueue) {
match &mut self.queue {
InternalQueue::CommandQueue(queue) => queue.bytes.append(&mut other.bytes),
InternalQueue::RawCommandQueue(queue) => {
unsafe { queue.bytes.as_mut() }.append(&mut other.bytes);
}
}
}
#[track_caller]
pub fn spawn_empty(&mut self) -> EntityCommands<'_> {
let entity = self.allocator.alloc();
let caller = MaybeLocation::caller();
self.queue(move |world: &mut World| {
world.spawn_empty_at_with_caller(entity, caller).map(|_| ())
});
self.entity(entity)
}
#[track_caller]
pub fn spawn<T: Bundle>(&mut self, bundle: T) -> EntityCommands<'_> {
let entity = self.allocator.alloc();
let caller = MaybeLocation::caller();
self.queue(move |world: &mut World| {
move_as_ptr!(bundle);
world
.spawn_at_with_caller(entity, bundle, caller)
.map(|_| ())
});
self.entity(entity)
}
#[inline]
#[track_caller]
pub fn entity(&mut self, entity: Entity) -> EntityCommands<'_> {
EntityCommands {
entity,
commands: self.reborrow(),
}
}
#[inline]
#[track_caller]
pub fn get_entity(&mut self, entity: Entity) -> Result<EntityCommands<'_>, InvalidEntityError> {
let _location = self.entities.get(entity)?;
Ok(EntityCommands {
entity,
commands: self.reborrow(),
})
}
#[inline]
#[track_caller]
pub fn get_spawned_entity(
&mut self,
entity: Entity,
) -> Result<EntityCommands<'_>, EntityNotSpawnedError> {
let _location = self.entities.get_spawned(entity)?;
Ok(EntityCommands {
entity,
commands: self.reborrow(),
})
}
#[track_caller]
pub fn spawn_batch<I>(&mut self, batch: I)
where
I: IntoIterator + Send + Sync + 'static,
I::Item: Bundle<Effect: NoBundleEffect>,
{
self.queue(command::spawn_batch(batch));
}
pub fn queue<C: Command<T> + HandleError<T>, T>(&mut self, command: C) {
self.queue_internal(command.handle_error());
}
pub fn queue_handled<C: Command<T> + HandleError<T>, T>(
&mut self,
command: C,
error_handler: fn(BevyError, ErrorContext),
) {
self.queue_internal(command.handle_error_with(error_handler));
}
pub fn queue_silenced<C: Command<T> + HandleError<T>, T>(&mut self, command: C) {
self.queue_internal(command.ignore_error());
}
fn queue_internal(&mut self, command: impl Command) {
match &mut self.queue {
InternalQueue::CommandQueue(queue) => {
queue.push(command);
}
InternalQueue::RawCommandQueue(queue) => {
unsafe {
queue.push(command);
}
}
}
}
#[track_caller]
pub fn insert_batch<I, B>(&mut self, batch: I)
where
I: IntoIterator<Item = (Entity, B)> + Send + Sync + 'static,
B: Bundle<Effect: NoBundleEffect>,
{
self.queue(command::insert_batch(batch, InsertMode::Replace));
}
#[track_caller]
pub fn insert_batch_if_new<I, B>(&mut self, batch: I)
where
I: IntoIterator<Item = (Entity, B)> + Send + Sync + 'static,
B: Bundle<Effect: NoBundleEffect>,
{
self.queue(command::insert_batch(batch, InsertMode::Keep));
}
#[track_caller]
pub fn try_insert_batch<I, B>(&mut self, batch: I)
where
I: IntoIterator<Item = (Entity, B)> + Send + Sync + 'static,
B: Bundle<Effect: NoBundleEffect>,
{
self.queue(command::insert_batch(batch, InsertMode::Replace).handle_error_with(warn));
}
#[track_caller]
pub fn try_insert_batch_if_new<I, B>(&mut self, batch: I)
where
I: IntoIterator<Item = (Entity, B)> + Send + Sync + 'static,
B: Bundle<Effect: NoBundleEffect>,
{
self.queue(command::insert_batch(batch, InsertMode::Keep).handle_error_with(warn));
}
#[track_caller]
pub fn init_resource<R: Resource + FromWorld>(&mut self) {
self.queue(command::init_resource::<R>());
}
#[track_caller]
pub fn insert_resource<R: Resource>(&mut self, resource: R) {
self.queue(command::insert_resource(resource));
}
pub fn remove_resource<R: Resource>(&mut self) {
self.queue(command::remove_resource::<R>());
}
pub fn run_system(&mut self, id: SystemId) {
self.queue(command::run_system(id).handle_error_with(warn));
}
pub fn run_system_with<I>(&mut self, id: SystemId<I>, input: I::Inner<'static>)
where
I: SystemInput<Inner<'static>: Send> + 'static,
{
self.queue(command::run_system_with(id, input).handle_error_with(warn));
}
pub fn register_system<I, O, M>(
&mut self,
system: impl IntoSystem<I, O, M> + 'static,
) -> SystemId<I, O>
where
I: SystemInput + Send + 'static,
O: Send + 'static,
{
let entity = self.spawn_empty().id();
let system = RegisteredSystem::<I, O>::new(Box::new(IntoSystem::into_system(system)));
self.entity(entity).insert(system);
SystemId::from_entity(entity)
}
pub fn unregister_system<I, O>(&mut self, system_id: SystemId<I, O>)
where
I: SystemInput + Send + 'static,
O: Send + 'static,
{
self.queue(command::unregister_system(system_id).handle_error_with(warn));
}
pub fn unregister_system_cached<I, O, M, S>(&mut self, system: S)
where
I: SystemInput + Send + 'static,
O: 'static,
M: 'static,
S: IntoSystem<I, O, M> + Send + 'static,
{
self.queue(command::unregister_system_cached(system).handle_error_with(warn));
}
pub fn run_system_cached<M, S>(&mut self, system: S)
where
M: 'static,
S: IntoSystem<(), (), M> + Send + 'static,
{
self.queue(command::run_system_cached(system).handle_error_with(warn));
}
pub fn run_system_cached_with<I, M, S>(&mut self, system: S, input: I::Inner<'static>)
where
I: SystemInput<Inner<'static>: Send> + Send + 'static,
M: 'static,
S: IntoSystem<I, (), M> + Send + 'static,
{
self.queue(command::run_system_cached_with(system, input).handle_error_with(warn));
}
#[track_caller]
pub fn trigger<'a>(&mut self, event: impl Event<Trigger<'a>: Default>) {
self.queue(command::trigger(event));
}
#[track_caller]
pub fn trigger_with<E: Event<Trigger<'static>: Send + Sync>>(
&mut self,
event: E,
trigger: E::Trigger<'static>,
) {
self.queue(command::trigger_with(event, trigger));
}
pub fn add_observer<E: Event, B: Bundle, M>(
&mut self,
observer: impl IntoObserverSystem<E, B, M>,
) -> EntityCommands<'_> {
self.spawn(Observer::new(observer))
}
#[track_caller]
pub fn write_message<M: Message>(&mut self, message: M) -> &mut Self {
self.queue(command::write_message(message));
self
}
pub fn run_schedule(&mut self, label: impl ScheduleLabel) {
self.queue(command::run_schedule(label).handle_error_with(warn));
}
}
pub struct EntityCommands<'a> {
pub(crate) entity: Entity,
pub(crate) commands: Commands<'a, 'a>,
}
impl<'a> EntityCommands<'a> {
#[inline]
#[must_use = "Omit the .id() call if you do not need to store the `Entity` identifier."]
pub fn id(&self) -> Entity {
self.entity
}
pub fn reborrow(&mut self) -> EntityCommands<'_> {
EntityCommands {
entity: self.entity,
commands: self.commands.reborrow(),
}
}
pub fn entry<T: Component>(&mut self) -> EntityEntryCommands<'_, T> {
EntityEntryCommands {
entity_commands: self.reborrow(),
marker: PhantomData,
}
}
#[track_caller]
pub fn insert(&mut self, bundle: impl Bundle) -> &mut Self {
self.queue(entity_command::insert(bundle, InsertMode::Replace))
}
#[track_caller]
pub fn insert_if<F>(&mut self, bundle: impl Bundle, condition: F) -> &mut Self
where
F: FnOnce() -> bool,
{
if condition() {
self.insert(bundle)
} else {
self
}
}
#[track_caller]
pub fn insert_if_new(&mut self, bundle: impl Bundle) -> &mut Self {
self.queue(entity_command::insert(bundle, InsertMode::Keep))
}
#[track_caller]
pub fn insert_if_new_and<F>(&mut self, bundle: impl Bundle, condition: F) -> &mut Self
where
F: FnOnce() -> bool,
{
if condition() {
self.insert_if_new(bundle)
} else {
self
}
}
#[track_caller]
pub unsafe fn insert_by_id<T: Send + 'static>(
&mut self,
component_id: ComponentId,
value: T,
) -> &mut Self {
self.queue(
unsafe { entity_command::insert_by_id(component_id, value, InsertMode::Replace) },
)
}
#[track_caller]
pub unsafe fn try_insert_by_id<T: Send + 'static>(
&mut self,
component_id: ComponentId,
value: T,
) -> &mut Self {
self.queue_silenced(
unsafe { entity_command::insert_by_id(component_id, value, InsertMode::Replace) },
)
}
#[track_caller]
pub fn try_insert(&mut self, bundle: impl Bundle) -> &mut Self {
self.queue_silenced(entity_command::insert(bundle, InsertMode::Replace))
}
#[track_caller]
pub fn try_insert_if<F>(&mut self, bundle: impl Bundle, condition: F) -> &mut Self
where
F: FnOnce() -> bool,
{
if condition() {
self.try_insert(bundle)
} else {
self
}
}
#[track_caller]
pub fn try_insert_if_new_and<F>(&mut self, bundle: impl Bundle, condition: F) -> &mut Self
where
F: FnOnce() -> bool,
{
if condition() {
self.try_insert_if_new(bundle)
} else {
self
}
}
#[track_caller]
pub fn try_insert_if_new(&mut self, bundle: impl Bundle) -> &mut Self {
self.queue_silenced(entity_command::insert(bundle, InsertMode::Keep))
}
#[track_caller]
pub fn remove<B: Bundle>(&mut self) -> &mut Self {
self.queue_handled(entity_command::remove::<B>(), warn)
}
#[track_caller]
pub fn remove_if<B: Bundle>(&mut self, condition: impl FnOnce() -> bool) -> &mut Self {
if condition() {
self.remove::<B>()
} else {
self
}
}
#[track_caller]
pub fn try_remove_if<B: Bundle>(&mut self, condition: impl FnOnce() -> bool) -> &mut Self {
if condition() {
self.try_remove::<B>()
} else {
self
}
}
pub fn try_remove<B: Bundle>(&mut self) -> &mut Self {
self.queue_silenced(entity_command::remove::<B>())
}
#[track_caller]
pub fn remove_with_requires<B: Bundle>(&mut self) -> &mut Self {
self.queue(entity_command::remove_with_requires::<B>())
}
#[track_caller]
pub fn remove_by_id(&mut self, component_id: ComponentId) -> &mut Self {
self.queue(entity_command::remove_by_id(component_id))
}
#[track_caller]
pub fn clear(&mut self) -> &mut Self {
self.queue(entity_command::clear())
}
#[track_caller]
pub fn despawn(&mut self) {
self.queue_handled(entity_command::despawn(), warn);
}
pub fn try_despawn(&mut self) {
self.queue_silenced(entity_command::despawn());
}
pub fn queue<C: EntityCommand<T> + CommandWithEntity<M>, T, M>(
&mut self,
command: C,
) -> &mut Self {
self.commands.queue(command.with_entity(self.entity));
self
}
pub fn queue_handled<C: EntityCommand<T> + CommandWithEntity<M>, T, M>(
&mut self,
command: C,
error_handler: fn(BevyError, ErrorContext),
) -> &mut Self {
self.commands
.queue_handled(command.with_entity(self.entity), error_handler);
self
}
pub fn queue_silenced<C: EntityCommand<T> + CommandWithEntity<M>, T, M>(
&mut self,
command: C,
) -> &mut Self {
self.commands
.queue_silenced(command.with_entity(self.entity));
self
}
#[track_caller]
pub fn retain<B: Bundle>(&mut self) -> &mut Self {
self.queue(entity_command::retain::<B>())
}
pub fn log_components(&mut self) -> &mut Self {
self.queue(entity_command::log_components())
}
pub fn commands(&mut self) -> Commands<'_, '_> {
self.commands.reborrow()
}
pub fn commands_mut(&mut self) -> &mut Commands<'a, 'a> {
&mut self.commands
}
pub fn observe<E: EntityEvent, B: Bundle, M>(
&mut self,
observer: impl IntoObserverSystem<E, B, M>,
) -> &mut Self {
self.queue(entity_command::observe(observer))
}
pub fn clone_with_opt_out(
&mut self,
target: Entity,
config: impl FnOnce(&mut EntityClonerBuilder<OptOut>) + Send + Sync + 'static,
) -> &mut Self {
self.queue(entity_command::clone_with_opt_out(target, config))
}
pub fn clone_with_opt_in(
&mut self,
target: Entity,
config: impl FnOnce(&mut EntityClonerBuilder<OptIn>) + Send + Sync + 'static,
) -> &mut Self {
self.queue(entity_command::clone_with_opt_in(target, config))
}
pub fn clone_and_spawn(&mut self) -> EntityCommands<'_> {
self.clone_and_spawn_with_opt_out(|_| {})
}
pub fn clone_and_spawn_with_opt_out(
&mut self,
config: impl FnOnce(&mut EntityClonerBuilder<OptOut>) + Send + Sync + 'static,
) -> EntityCommands<'_> {
let entity_clone = self.commands().spawn_empty().id();
self.clone_with_opt_out(entity_clone, config);
EntityCommands {
commands: self.commands_mut().reborrow(),
entity: entity_clone,
}
}
pub fn clone_and_spawn_with_opt_in(
&mut self,
config: impl FnOnce(&mut EntityClonerBuilder<OptIn>) + Send + Sync + 'static,
) -> EntityCommands<'_> {
let entity_clone = self.commands().spawn_empty().id();
self.clone_with_opt_in(entity_clone, config);
EntityCommands {
commands: self.commands_mut().reborrow(),
entity: entity_clone,
}
}
pub fn clone_components<B: Bundle>(&mut self, target: Entity) -> &mut Self {
self.queue(entity_command::clone_components::<B>(target))
}
pub fn move_components<B: Bundle>(&mut self, target: Entity) -> &mut Self {
self.queue(entity_command::move_components::<B>(target))
}
#[track_caller]
pub fn trigger<'t, E: EntityEvent<Trigger<'t>: Default>>(
&mut self,
event_fn: impl FnOnce(Entity) -> E,
) -> &mut Self {
let event = (event_fn)(self.entity);
self.commands.trigger(event);
self
}
}
pub struct EntityEntryCommands<'a, T> {
entity_commands: EntityCommands<'a>,
marker: PhantomData<T>,
}
impl<'a, T: Component<Mutability = Mutable>> EntityEntryCommands<'a, T> {
pub fn and_modify(&mut self, modify: impl FnOnce(Mut<T>) + Send + Sync + 'static) -> &mut Self {
self.entity_commands
.queue(move |mut entity: EntityWorldMut| {
if let Some(value) = entity.get_mut() {
modify(value);
}
});
self
}
}
impl<'a, T: Component> EntityEntryCommands<'a, T> {
#[track_caller]
pub fn or_insert(&mut self, default: T) -> &mut Self {
self.entity_commands.insert_if_new(default);
self
}
#[track_caller]
pub fn or_try_insert(&mut self, default: T) -> &mut Self {
self.entity_commands.try_insert_if_new(default);
self
}
#[track_caller]
pub fn or_insert_with<F>(&mut self, default: F) -> &mut Self
where
F: FnOnce() -> T + Send + 'static,
{
self.entity_commands
.queue(entity_command::insert_with(default, InsertMode::Keep));
self
}
#[track_caller]
pub fn or_try_insert_with<F>(&mut self, default: F) -> &mut Self
where
F: FnOnce() -> T + Send + 'static,
{
self.entity_commands
.queue_silenced(entity_command::insert_with(default, InsertMode::Keep));
self
}
#[track_caller]
pub fn or_default(&mut self) -> &mut Self
where
T: Default,
{
self.or_insert_with(T::default)
}
#[track_caller]
pub fn or_from_world(&mut self) -> &mut Self
where
T: FromWorld,
{
self.entity_commands
.queue(entity_command::insert_from_world::<T>(InsertMode::Keep));
self
}
pub fn entity(&mut self) -> EntityCommands<'_> {
self.entity_commands.reborrow()
}
}
#[cfg(test)]
mod tests {
use crate::{
component::Component,
resource::Resource,
system::Commands,
world::{CommandQueue, FromWorld, World},
};
use alloc::{string::String, sync::Arc, vec, vec::Vec};
use core::{
any::TypeId,
sync::atomic::{AtomicUsize, Ordering},
};
#[expect(
dead_code,
reason = "This struct is used to test how `Drop` behavior works in regards to SparseSet storage, and as such is solely a wrapper around `DropCk` to make it use the SparseSet storage. Because of this, the inner field is intentionally never read."
)]
#[derive(Component)]
#[component(storage = "SparseSet")]
struct SparseDropCk(DropCk);
#[derive(Component)]
struct DropCk(Arc<AtomicUsize>);
impl DropCk {
fn new_pair() -> (Self, Arc<AtomicUsize>) {
let atomic = Arc::new(AtomicUsize::new(0));
(DropCk(atomic.clone()), atomic)
}
}
impl Drop for DropCk {
fn drop(&mut self) {
self.0.as_ref().fetch_add(1, Ordering::Relaxed);
}
}
#[derive(Component)]
struct W<T>(T);
#[derive(Resource)]
struct V<T>(T);
fn simple_command(world: &mut World) {
world.spawn((W(0u32), W(42u64)));
}
impl FromWorld for W<String> {
fn from_world(world: &mut World) -> Self {
let v = world.resource::<V<usize>>();
Self("*".repeat(v.0))
}
}
impl Default for W<u8> {
fn default() -> Self {
unreachable!()
}
}
#[test]
fn entity_commands_entry() {
let mut world = World::default();
let mut queue = CommandQueue::default();
let mut commands = Commands::new(&mut queue, &world);
let entity = commands.spawn_empty().id();
commands
.entity(entity)
.entry::<W<u32>>()
.and_modify(|_| unreachable!());
queue.apply(&mut world);
assert!(!world.entity(entity).contains::<W<u32>>());
let mut commands = Commands::new(&mut queue, &world);
commands
.entity(entity)
.entry::<W<u32>>()
.or_insert(W(0))
.and_modify(|mut val| {
val.0 = 21;
});
queue.apply(&mut world);
assert_eq!(21, world.get::<W<u32>>(entity).unwrap().0);
let mut commands = Commands::new(&mut queue, &world);
commands
.entity(entity)
.entry::<W<u64>>()
.and_modify(|_| unreachable!())
.or_insert(W(42));
queue.apply(&mut world);
assert_eq!(42, world.get::<W<u64>>(entity).unwrap().0);
world.insert_resource(V(5_usize));
let mut commands = Commands::new(&mut queue, &world);
commands.entity(entity).entry::<W<String>>().or_from_world();
queue.apply(&mut world);
assert_eq!("*****", &world.get::<W<String>>(entity).unwrap().0);
let mut commands = Commands::new(&mut queue, &world);
let id = commands.entity(entity).entry::<W<u64>>().entity().id();
queue.apply(&mut world);
assert_eq!(id, entity);
let mut commands = Commands::new(&mut queue, &world);
commands
.entity(entity)
.entry::<W<u8>>()
.or_insert_with(|| W(5))
.or_insert_with(|| unreachable!())
.or_try_insert_with(|| unreachable!())
.or_default()
.or_from_world();
queue.apply(&mut world);
assert_eq!(5, world.get::<W<u8>>(entity).unwrap().0);
}
#[test]
fn commands() {
let mut world = World::default();
let mut command_queue = CommandQueue::default();
let entity = Commands::new(&mut command_queue, &world)
.spawn((W(1u32), W(2u64)))
.id();
command_queue.apply(&mut world);
assert_eq!(world.query::<&W<u32>>().query(&world).count(), 1);
let results = world
.query::<(&W<u32>, &W<u64>)>()
.iter(&world)
.map(|(a, b)| (a.0, b.0))
.collect::<Vec<_>>();
assert_eq!(results, vec![(1u32, 2u64)]);
{
let mut commands = Commands::new(&mut command_queue, &world);
commands.entity(entity).despawn();
commands.entity(entity).despawn(); }
command_queue.apply(&mut world);
let results2 = world
.query::<(&W<u32>, &W<u64>)>()
.iter(&world)
.map(|(a, b)| (a.0, b.0))
.collect::<Vec<_>>();
assert_eq!(results2, vec![]);
{
let mut commands = Commands::new(&mut command_queue, &world);
commands.queue(|world: &mut World| {
world.spawn((W(42u32), W(0u64)));
});
commands.queue(simple_command);
}
command_queue.apply(&mut world);
let results3 = world
.query::<(&W<u32>, &W<u64>)>()
.iter(&world)
.map(|(a, b)| (a.0, b.0))
.collect::<Vec<_>>();
assert_eq!(results3, vec![(42u32, 0u64), (0u32, 42u64)]);
}
#[test]
fn insert_components() {
let mut world = World::default();
let mut command_queue1 = CommandQueue::default();
let entity = Commands::new(&mut command_queue1, &world)
.spawn(())
.insert_if(W(1u8), || true)
.insert_if(W(2u8), || false)
.insert_if_new(W(1u16))
.insert_if_new(W(2u16))
.insert_if_new_and(W(1u32), || false)
.insert_if_new_and(W(2u32), || true)
.insert_if_new_and(W(3u32), || true)
.id();
command_queue1.apply(&mut world);
let results = world
.query::<(&W<u8>, &W<u16>, &W<u32>)>()
.iter(&world)
.map(|(a, b, c)| (a.0, b.0, c.0))
.collect::<Vec<_>>();
assert_eq!(results, vec![(1u8, 1u16, 2u32)]);
Commands::new(&mut command_queue1, &world)
.entity(entity)
.try_insert_if_new_and(W(1u64), || true);
let mut command_queue2 = CommandQueue::default();
Commands::new(&mut command_queue2, &world)
.entity(entity)
.despawn();
command_queue2.apply(&mut world);
command_queue1.apply(&mut world);
}
#[test]
fn remove_components() {
let mut world = World::default();
let mut command_queue = CommandQueue::default();
let (dense_dropck, dense_is_dropped) = DropCk::new_pair();
let (sparse_dropck, sparse_is_dropped) = DropCk::new_pair();
let sparse_dropck = SparseDropCk(sparse_dropck);
let entity = Commands::new(&mut command_queue, &world)
.spawn((W(1u32), W(2u64), dense_dropck, sparse_dropck))
.id();
command_queue.apply(&mut world);
let results_before = world
.query::<(&W<u32>, &W<u64>)>()
.iter(&world)
.map(|(a, b)| (a.0, b.0))
.collect::<Vec<_>>();
assert_eq!(results_before, vec![(1u32, 2u64)]);
Commands::new(&mut command_queue, &world)
.entity(entity)
.remove::<W<u32>>()
.remove::<(W<u32>, W<u64>, SparseDropCk, DropCk)>();
assert_eq!(dense_is_dropped.load(Ordering::Relaxed), 0);
assert_eq!(sparse_is_dropped.load(Ordering::Relaxed), 0);
command_queue.apply(&mut world);
assert_eq!(dense_is_dropped.load(Ordering::Relaxed), 1);
assert_eq!(sparse_is_dropped.load(Ordering::Relaxed), 1);
let results_after = world
.query::<(&W<u32>, &W<u64>)>()
.iter(&world)
.map(|(a, b)| (a.0, b.0))
.collect::<Vec<_>>();
assert_eq!(results_after, vec![]);
let results_after_u64 = world
.query::<&W<u64>>()
.iter(&world)
.map(|v| v.0)
.collect::<Vec<_>>();
assert_eq!(results_after_u64, vec![]);
}
#[test]
fn remove_components_by_id() {
let mut world = World::default();
let mut command_queue = CommandQueue::default();
let (dense_dropck, dense_is_dropped) = DropCk::new_pair();
let (sparse_dropck, sparse_is_dropped) = DropCk::new_pair();
let sparse_dropck = SparseDropCk(sparse_dropck);
let entity = Commands::new(&mut command_queue, &world)
.spawn((W(1u32), W(2u64), dense_dropck, sparse_dropck))
.id();
command_queue.apply(&mut world);
let results_before = world
.query::<(&W<u32>, &W<u64>)>()
.iter(&world)
.map(|(a, b)| (a.0, b.0))
.collect::<Vec<_>>();
assert_eq!(results_before, vec![(1u32, 2u64)]);
Commands::new(&mut command_queue, &world)
.entity(entity)
.remove_by_id(world.components().get_id(TypeId::of::<W<u32>>()).unwrap())
.remove_by_id(world.components().get_id(TypeId::of::<W<u64>>()).unwrap())
.remove_by_id(world.components().get_id(TypeId::of::<DropCk>()).unwrap())
.remove_by_id(
world
.components()
.get_id(TypeId::of::<SparseDropCk>())
.unwrap(),
);
assert_eq!(dense_is_dropped.load(Ordering::Relaxed), 0);
assert_eq!(sparse_is_dropped.load(Ordering::Relaxed), 0);
command_queue.apply(&mut world);
assert_eq!(dense_is_dropped.load(Ordering::Relaxed), 1);
assert_eq!(sparse_is_dropped.load(Ordering::Relaxed), 1);
let results_after = world
.query::<(&W<u32>, &W<u64>)>()
.iter(&world)
.map(|(a, b)| (a.0, b.0))
.collect::<Vec<_>>();
assert_eq!(results_after, vec![]);
let results_after_u64 = world
.query::<&W<u64>>()
.iter(&world)
.map(|v| v.0)
.collect::<Vec<_>>();
assert_eq!(results_after_u64, vec![]);
}
#[test]
fn remove_resources() {
let mut world = World::default();
let mut queue = CommandQueue::default();
{
let mut commands = Commands::new(&mut queue, &world);
commands.insert_resource(V(123i32));
commands.insert_resource(V(456.0f64));
}
queue.apply(&mut world);
assert!(world.contains_resource::<V<i32>>());
assert!(world.contains_resource::<V<f64>>());
{
let mut commands = Commands::new(&mut queue, &world);
commands.remove_resource::<V<i32>>();
}
queue.apply(&mut world);
assert!(!world.contains_resource::<V<i32>>());
assert!(world.contains_resource::<V<f64>>());
}
#[test]
fn remove_component_with_required_components() {
#[derive(Component)]
#[require(Y)]
struct X;
#[derive(Component, Default)]
struct Y;
#[derive(Component)]
struct Z;
let mut world = World::default();
let mut queue = CommandQueue::default();
let e = {
let mut commands = Commands::new(&mut queue, &world);
commands.spawn((X, Z)).id()
};
queue.apply(&mut world);
assert!(world.get::<Y>(e).is_some());
assert!(world.get::<X>(e).is_some());
assert!(world.get::<Z>(e).is_some());
{
let mut commands = Commands::new(&mut queue, &world);
commands.entity(e).remove_with_requires::<X>();
}
queue.apply(&mut world);
assert!(world.get::<Y>(e).is_none());
assert!(world.get::<X>(e).is_none());
assert!(world.get::<Z>(e).is_some());
}
#[test]
fn unregister_system_cached_commands() {
let mut world = World::default();
let mut queue = CommandQueue::default();
fn nothing() {}
let resources = world.iter_resources().count();
let id = world.register_system_cached(nothing);
assert_eq!(world.iter_resources().count(), resources + 1);
assert!(world.get_entity(id.entity).is_ok());
let mut commands = Commands::new(&mut queue, &world);
commands.unregister_system_cached(nothing);
queue.apply(&mut world);
assert_eq!(world.iter_resources().count(), resources);
assert!(world.get_entity(id.entity).is_err());
}
fn is_send<T: Send>() {}
fn is_sync<T: Sync>() {}
#[test]
fn test_commands_are_send_and_sync() {
is_send::<Commands>();
is_sync::<Commands>();
}
#[test]
fn append() {
let mut world = World::default();
let mut queue_1 = CommandQueue::default();
{
let mut commands = Commands::new(&mut queue_1, &world);
commands.insert_resource(V(123i32));
}
let mut queue_2 = CommandQueue::default();
{
let mut commands = Commands::new(&mut queue_2, &world);
commands.insert_resource(V(456.0f64));
}
queue_1.append(&mut queue_2);
queue_1.apply(&mut world);
assert!(world.contains_resource::<V<i32>>());
assert!(world.contains_resource::<V<f64>>());
}
#[test]
fn track_spawn_ticks() {
let mut world = World::default();
world.increment_change_tick();
let expected = world.change_tick();
let id = world.commands().spawn_empty().id();
world.flush();
assert_eq!(
Some(expected),
world.entities().entity_get_spawn_or_despawn_tick(id)
);
}
}