use std::collections::HashMap;
use std::sync::{Arc, Mutex};
#[derive(Debug, Default)]
pub struct CollisionIndex {
grid: HashMap<(i32, i32), Vec<OwnedBox>>,
generation: u64,
frame: Option<FrameKey>,
stale: bool,
}
type OwnedBox = ([f32; 4], u64);
type FrameKey = ([f32; 16], (u32, u32), [f64; 3]);
pub(crate) fn next_owner() -> u64 {
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
}
pub type SharedCollision = Arc<Mutex<CollisionIndex>>;
pub type SharedVisibility = Arc<Mutex<Vec<bool>>>;
const CELL: f32 = 64.0;
impl CollisionIndex {
pub fn new() -> Self {
Self::default()
}
pub fn shared(self) -> SharedCollision {
Arc::new(Mutex::new(self))
}
pub fn clear(&mut self) {
self.grid.clear();
self.generation += 1;
self.frame = None;
self.stale = false;
}
pub fn begin_frame(&mut self, view: &super::MarkView) -> bool {
let key = (view.view_proj, view.viewport, view.origin.position);
if self.frame == Some(key) && !self.stale {
return false;
}
self.clear();
self.frame = Some(key);
true
}
pub fn len(&self) -> usize {
let mut seen: Vec<([u32; 4], u64)> = self
.grid
.values()
.flatten()
.map(|(r, o)| (r.map(f32::to_bits), *o))
.collect();
seen.sort_unstable();
seen.dedup();
seen.len()
}
pub fn is_empty(&self) -> bool {
self.grid.values().all(Vec::is_empty)
}
pub fn invalidate(&mut self) {
self.stale = true;
}
pub fn remove_owner(&mut self, owner: u64) {
for boxes in self.grid.values_mut() {
boxes.retain(|b| b.1 != owner);
}
}
pub fn generation(&self) -> u64 {
self.generation
}
fn cells(r: [f32; 4]) -> impl Iterator<Item = (i32, i32)> {
let (cx0, cy0) = ((r[0] / CELL).floor() as i32, (r[1] / CELL).floor() as i32);
let (cx1, cy1) = ((r[2] / CELL).floor() as i32, (r[3] / CELL).floor() as i32);
(cy0..=cy1).flat_map(move |y| (cx0..=cx1).map(move |x| (x, y)))
}
pub fn collides(&self, r: [f32; 4]) -> bool {
Self::cells(r).any(|c| {
self.grid.get(&c).is_some_and(|boxes| {
boxes
.iter()
.any(|(o, _)| r[0] < o[2] && o[0] < r[2] && r[1] < o[3] && o[1] < r[3])
})
})
}
pub fn insert(&mut self, r: [f32; 4]) {
self.insert_owned(0, r);
}
pub fn try_insert(&mut self, r: [f32; 4]) -> bool {
self.try_insert_owned(0, r)
}
pub fn insert_owned(&mut self, owner: u64, r: [f32; 4]) {
for c in Self::cells(r) {
self.grid.entry(c).or_default().push((r, owner));
}
}
pub fn try_insert_owned(&mut self, owner: u64, r: [f32; 4]) -> bool {
if self.collides(r) {
return false;
}
self.insert_owned(owner, r);
true
}
pub(crate) fn reclaim(&mut self, owner: u64, placed_generation: Option<u64>) {
if placed_generation == Some(self.generation) {
self.remove_owner(owner);
self.stale = true;
}
}
}