jagua_rs/collision_detection/hazards/
collector.rs

1use crate::collision_detection::hazards::filter::HazardFilter;
2use crate::collision_detection::hazards::{HazKey, HazardEntity};
3use slotmap::SecondaryMap;
4
5/// Trait for structs that can track and store detected [`Hazard`](crate::collision_detection::hazards::Hazard)s.
6/// Used in 'collision collection' queries to avoid having to repeatedly check hazards induced by one that has already been detected.
7pub trait HazardCollector: HazardFilter {
8    fn contains_key(&self, hkey: HazKey) -> bool;
9
10    fn contains_entity(&self, entity: &HazardEntity) -> bool {
11        self.iter().any(|(_, e)| e == entity)
12    }
13
14    fn insert(&mut self, hkey: HazKey, entity: HazardEntity);
15
16    fn remove_by_key(&mut self, hkey: HazKey);
17
18    fn remove_by_entity(&mut self, entity: &HazardEntity) {
19        let hkey = self
20            .iter()
21            .find(|(_, v)| *v == entity)
22            .map(|(hkey, _)| hkey)
23            .expect("HazardEntity not found in collector");
24        self.remove_by_key(hkey);
25    }
26
27    fn is_empty(&self) -> bool {
28        self.len() == 0
29    }
30
31    fn len(&self) -> usize;
32
33    fn iter(&self) -> impl Iterator<Item = (HazKey, &HazardEntity)>;
34
35    fn keys(&self) -> impl Iterator<Item = HazKey> {
36        self.iter().map(|(k, _)| k)
37    }
38
39    fn entities(&self) -> impl Iterator<Item = &HazardEntity> {
40        self.iter().map(|(_, e)| e)
41    }
42}
43
44/// A basic implementation of a [`HazardCollector`] using a `SecondaryMap` to store hazards by their `HazKey`.
45pub type BasicHazardCollector = SecondaryMap<HazKey, HazardEntity>;
46
47impl HazardCollector for BasicHazardCollector {
48    fn contains_key(&self, hkey: HazKey) -> bool {
49        self.contains_key(hkey)
50    }
51
52    fn insert(&mut self, hkey: HazKey, entity: HazardEntity) {
53        self.insert(hkey, entity);
54    }
55
56    fn remove_by_key(&mut self, hkey: HazKey) {
57        self.remove(hkey);
58    }
59
60    fn len(&self) -> usize {
61        self.len()
62    }
63
64    fn iter(&self) -> impl Iterator<Item = (HazKey, &HazardEntity)> {
65        self.iter()
66    }
67}