use bevy::ecs::system::SystemState;
use bevy::ecs::world::EntityWorldMut;
use bevy::prelude::*;
use crate::attributes_mut::AttributesMut;
use crate::writer::BoundAttributesMut;
pub trait AttributeCommandsExt {
fn attrs(&mut self, f: impl FnOnce(&mut BoundAttributesMut) + Send + 'static) -> &mut Self;
}
impl AttributeCommandsExt for EntityCommands<'_> {
fn attrs(&mut self, f: impl FnOnce(&mut BoundAttributesMut) + Send + 'static) -> &mut Self {
self.queue(AttrsEntityCommand { f: Box::new(f) });
self
}
}
struct AttrsEntityCommand {
f: Box<dyn FnOnce(&mut BoundAttributesMut) + Send + 'static>,
}
impl EntityCommand for AttrsEntityCommand {
type Out = ();
fn apply(self, entity_world: EntityWorldMut<'_>) {
let entity = entity_world.id();
let world = entity_world.into_world_mut();
let mut state = SystemState::<AttributesMut>::new(world);
let Ok(mut attrs_mut) = state.get_mut(world) else {
debug!("could not get attributes for {entity}. skipping...");
return;
};
let mut bound = BoundAttributesMut {
entity,
attrs: &mut attrs_mut,
};
(self.f)(&mut bound);
state.apply(world);
}
}