use nadir_collision::{CollisionWorld, Contact, TileGrid, Triggers, move_and_slide};
use nadir_core::Vec2;
use nadir_ecs::{Entity, Events, SparseSet};
use crate::{Collider, Transform, Velocity};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct TriggerEnter {
pub trigger: Entity,
pub other: Entity,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct TriggerExit {
pub trigger: Entity,
pub other: Entity,
}
const NONE: u32 = u32::MAX;
pub struct Collisions {
world: CollisionWorld,
entities: [Vec<Entity>; 2],
slots: [Vec<u32>; 2],
triggers: Triggers,
contacts: Vec<Contact>,
}
impl Collisions {
pub fn new() -> Self {
Self::with_world(CollisionWorld::new())
}
pub fn with_cell_size(cell_size: f32) -> Self {
Self::with_world(CollisionWorld::with_cell_size(cell_size))
}
fn with_world(world: CollisionWorld) -> Self {
Self {
world,
entities: [Vec::new(), Vec::new()],
slots: [Vec::new(), Vec::new()],
triggers: Triggers::new(),
contacts: Vec::new(),
}
}
pub fn world(&self) -> &CollisionWorld {
&self.world
}
pub fn grid(&self) -> &TileGrid {
self.world.grid()
}
pub fn grid_mut(&mut self) -> &mut TileGrid {
self.world.grid_mut()
}
pub fn set_grid(&mut self, grid: TileGrid) {
self.world.set_grid(grid);
}
pub fn entity(&self, index: u32) -> Entity {
match self.entities[0].get(index as usize) {
Some(&entity) => entity,
None => panic!(
"there is no collider {index}: the world has {}",
self.entities[0].len()
),
}
}
pub fn index(&self, entity: Entity) -> Option<u32> {
let index = *self.slots[0].get(entity.index() as usize)?;
(self.entities[0].get(index as usize) == Some(&entity)).then_some(index)
}
pub(crate) fn rebuild(
&mut self,
colliders: &SparseSet<Collider>,
transforms: &SparseSet<Transform>,
) {
self.entities.swap(0, 1);
self.slots.swap(0, 1);
let entities = &mut self.entities[0];
let slots = &mut self.slots[0];
entities.clear();
let colliders = colliders.iter().filter_map(|(entity, collider)| {
let transform = transforms.get(entity)?;
let at = entity.index() as usize;
if slots.len() <= at {
slots.resize(at + 1, NONE);
}
slots[at] = u32::try_from(entities.len()).unwrap_or(NONE);
entities.push(entity);
Some((bits(entity), transform.position, collider.0))
});
self.world.rebuild(colliders);
}
pub(crate) fn move_colliders(
&mut self,
velocities: &SparseSet<Velocity>,
transforms: &mut SparseSet<Transform>,
dt: f32,
) {
for (index, &entity) in (0u32..).zip(&self.entities[0]) {
let Some(velocity) = velocities.get(entity) else {
continue;
};
let delta = velocity.0 * dt;
let Some(transform) = transforms.get_mut(entity) else {
continue;
};
if delta == Vec2::ZERO {
continue;
}
let end = move_and_slide(
&self.world,
index,
transform.position,
delta,
&mut self.contacts,
);
self.world.set_position(index, end);
transform.position = end;
}
}
pub(crate) fn sync(&mut self, transforms: &SparseSet<Transform>) {
for (index, &entity) in (0u32..).zip(&self.entities[0]) {
if let Some(transform) = transforms.get(entity)
&& self.world.position(index) != transform.position
{
self.world.set_position(index, transform.position);
}
}
}
pub(crate) fn update_triggers(
&mut self,
enter: &mut Events<TriggerEnter>,
exit: &mut Events<TriggerExit>,
) {
self.triggers.update(&self.world);
for pair in self.triggers.entered() {
if let (Some(trigger), Some(other)) =
(self.resolve(0, pair.trigger), self.resolve(0, pair.other))
{
enter.send(TriggerEnter { trigger, other });
}
}
for pair in self.triggers.exited() {
if let (Some(trigger), Some(other)) =
(self.resolve(1, pair.trigger), self.resolve(1, pair.other))
{
exit.send(TriggerExit { trigger, other });
}
}
}
fn resolve(&self, which: usize, id: u64) -> Option<Entity> {
let index = *self.slots[which].get(id as u32 as usize)?;
let entity = *self.entities[which].get(index as usize)?;
(bits(entity) == id).then_some(entity)
}
}
impl Default for Collisions {
fn default() -> Self {
Self::new()
}
}
fn bits(entity: Entity) -> u64 {
(u64::from(entity.generation().get()) << 32) | u64::from(entity.index())
}