1use glam::Vec2;
5
6#[derive(Clone, Copy, Debug, Default, PartialEq)]
8pub struct Aabb {
9 pub min: Vec2,
10 pub max: Vec2,
11}
12
13impl Aabb {
14 #[must_use]
15 pub const fn new(min: Vec2, max: Vec2) -> Self {
16 Aabb { min, max }
17 }
18
19 fn intersects(&self, other: &Aabb) -> bool {
21 self.min.cmple(other.max).all() && other.min.cmple(self.max).all()
22 }
23}
24
25#[derive(Clone, Copy, Debug, PartialEq)]
27pub enum Shape {
28 Box(Aabb),
29 Circle { center: Vec2, radius: f32 },
30}
31
32impl Shape {
33 #[must_use]
35 pub(crate) fn bounds(&self) -> Aabb {
36 match *self {
37 Shape::Box(aabb) => aabb,
38 Shape::Circle { center, radius } => Aabb::new(center - radius, center + radius),
39 }
40 }
41
42 #[must_use]
45 pub(crate) fn intersects(&self, other: &Shape) -> bool {
46 match (self, other) {
47 (Shape::Box(a), Shape::Box(b)) => a.intersects(b),
48 (Shape::Circle { center: a, radius: ra }, Shape::Circle { center: b, radius: rb }) => {
49 let radii = ra + rb;
50 radii * radii > a.distance_squared(*b)
51 }
52 (Shape::Box(aabb), &Shape::Circle { center, radius })
53 | (&Shape::Circle { center, radius }, Shape::Box(aabb)) => {
54 let half_size = (aabb.max - aabb.min) / 2.0;
55 let distance = (center - (aabb.min + half_size)).abs();
56 if distance.cmpgt(half_size + radius).any() {
57 return false;
58 }
59 if distance.cmple(half_size).any() {
60 return true;
61 }
62 (distance - half_size).length_squared() <= radius * radius
63 }
64 }
65 }
66}
67
68#[derive(Clone, Debug)]
73pub(crate) struct Grid<T> {
74 size: Vec2,
75 cell_size: f32,
76 columns: usize,
77 rows: usize,
78 scale: Vec2,
80 elements: Vec<(T, Shape)>,
81 cells: Vec<Vec<u32>>,
83}
84
85impl<T> Grid<T> {
86 #[must_use]
88 pub(crate) fn new(size: Vec2, cell_size: f32) -> Self {
89 debug_assert!(size.cmpgt(Vec2::ZERO).all() && cell_size > 0.0);
90 let cell_counts = (size / cell_size).ceil().max(Vec2::ONE);
91 let (columns, rows) = (cell_counts.x as usize, cell_counts.y as usize);
92 Grid {
93 size,
94 cell_size,
95 columns,
96 rows,
97 scale: cell_counts / size,
98 elements: Vec::new(),
99 cells: (0..columns * rows).map(|_| Vec::new()).collect(),
100 }
101 }
102
103 pub(crate) fn reset(&mut self, size: Vec2, cell_size: f32) {
106 if size != self.size || cell_size != self.cell_size {
107 *self = Grid::new(size, cell_size);
108 return;
109 }
110 self.elements.clear();
111 for cell in &mut self.cells {
112 cell.clear();
113 }
114 }
115
116 #[must_use]
117 pub(crate) fn is_empty(&self) -> bool {
118 self.elements.is_empty()
119 }
120
121 pub(crate) fn insert(&mut self, value: T, shape: Shape) {
122 debug_assert!(self.elements.len() < u32::MAX as usize);
123 let id = self.elements.len() as u32;
124 let ((x1, y1), (x2, y2)) = self.cell_range(&shape.bounds());
125 for y in y1..=y2 {
126 for cell in self.cells[y * self.columns..][..self.columns].iter_mut().take(x2 + 1).skip(x1) {
127 cell.push(id);
128 }
129 }
130 self.elements.push((value, shape));
131 }
132
133 pub(crate) fn any(&self, shape: &Shape, mut hit: impl FnMut(&T) -> bool) -> bool {
137 self.find_candidate(&shape.bounds(), |id| {
138 let (value, other) = &self.elements[id as usize];
139 shape.intersects(other) && hit(value)
140 })
141 }
142
143 pub(crate) fn query(&self, shape: &Shape) -> impl Iterator<Item = (&T, &Shape)> {
146 let mut ids = Vec::new();
147 self.find_candidate(&shape.bounds(), |id| {
148 ids.push(id);
149 false
150 });
151 ids.sort_unstable();
152 ids.dedup();
153 ids.into_iter()
154 .map(|id| {
155 let (value, other) = &self.elements[id as usize];
156 (value, other)
157 })
158 .filter(move |(_, other)| shape.intersects(other))
159 }
160
161 fn find_candidate(&self, bounds: &Aabb, mut f: impl FnMut(u32) -> bool) -> bool {
165 if self.elements.is_empty() || bounds.max.cmplt(Vec2::ZERO).any() || bounds.min.cmpge(self.size).any() {
166 return false;
167 }
168 if bounds.min.cmple(Vec2::ZERO).all() && bounds.max.cmpge(self.size).all() {
169 return (0..self.elements.len() as u32).any(f);
171 }
172 let ((x1, y1), (x2, y2)) = self.cell_range(bounds);
173 (y1..=y2).any(|y| {
174 self.cells[y * self.columns..][..self.columns].iter().take(x2 + 1).skip(x1).flatten().any(|&id| f(id))
175 })
176 }
177
178 fn cell_range(&self, bounds: &Aabb) -> ((usize, usize), (usize, usize)) {
182 let cell = |p: Vec2| {
185 let p = p * self.scale;
186 ((p.x as usize).min(self.columns - 1), (p.y as usize).min(self.rows - 1))
187 };
188 (cell(bounds.min), cell(bounds.max))
189 }
190}
191
192#[cfg(test)]
193mod tests {
194 use super::*;
195
196 fn aabb(x1: f32, y1: f32, x2: f32, y2: f32) -> Shape {
197 Shape::Box(Aabb::new(Vec2::new(x1, y1), Vec2::new(x2, y2)))
198 }
199
200 fn circle(x: f32, y: f32, radius: f32) -> Shape {
201 Shape::Circle { center: Vec2::new(x, y), radius }
202 }
203
204 fn query(grid: &Grid<i16>, shape: Shape) -> Vec<i16> {
205 grid.query(&shape).map(|(value, _)| *value).collect()
206 }
207
208 #[test]
209 fn a_reversed_box_is_in_no_cell() {
210 let mut grid = Grid::new(Vec2::splat(100.0), 10.0);
211 grid.insert(0, aabb(60.0, 10.0, 20.0, 30.0));
212 assert!(!grid.any(&aabb(30.0, 15.0, 40.0, 25.0), |_| true));
213 assert_eq!(query(&grid, aabb(60.0, 10.0, 20.0, 30.0)), Vec::<i16>::new());
214 }
215
216 #[test]
217 fn indexes_boxes() {
218 let mut grid = Grid::new(Vec2::splat(100.0), 10.0);
219 grid.insert(0, aabb(4.0, 10.0, 6.0, 30.0));
220 grid.insert(1, aabb(4.0, 10.0, 30.0, 12.0));
221 grid.insert(2, aabb(-10.0, 30.0, 5.0, 35.0));
222
223 assert_eq!(query(&grid, aabb(4.0, 10.0, 5.0, 11.0)), [0, 1]);
224 assert_eq!(query(&grid, aabb(24.0, 10.0, 25.0, 11.0)), [1]);
225 assert_eq!(query(&grid, aabb(40.0, 40.0, 100.0, 100.0)), [0i16; 0]);
226 assert_eq!(query(&grid, aabb(-6.0, 0.0, 3.0, 100.0)), [2]);
227 assert_eq!(query(&grid, aabb(-1000.0, -1000.0, 1000.0, 1000.0)), [0, 1, 2]);
228 }
229
230 #[test]
231 fn reset_empties_the_grid() {
232 let mut grid = Grid::new(Vec2::splat(100.0), 10.0);
233 grid.insert(0, aabb(4.0, 10.0, 6.0, 30.0));
234 grid.insert(1, circle(50.0, 50.0, 5.0));
235 let everything = aabb(-1000.0, -1000.0, 1000.0, 1000.0);
236
237 grid.reset(Vec2::splat(100.0), 10.0);
238 assert!(grid.is_empty());
239 assert_eq!(query(&grid, everything), [0i16; 0]);
240 grid.insert(2, aabb(4.0, 10.0, 6.0, 30.0));
241 assert_eq!(query(&grid, everything), [2]);
242
243 grid.reset(Vec2::new(200.0, 50.0), 10.0);
244 assert!(grid.is_empty());
245 grid.insert(3, aabb(150.0, 10.0, 160.0, 20.0));
246 assert_eq!(query(&grid, aabb(155.0, 15.0, 156.0, 16.0)), [3]);
247 }
248
249 #[test]
250 fn duplicate_values() {
251 let mut grid = Grid::new(Vec2::splat(100.0), 10.0);
252 grid.insert(123, aabb(3.0, 4.0, 4.0, 4.0));
253 grid.insert(123, aabb(13.0, 13.0, 14.0, 14.0));
254 grid.insert(123, aabb(23.0, 23.0, 24.0, 24.0));
255
256 assert_eq!(query(&grid, aabb(0.0, 0.0, 30.0, 30.0)), [123, 123, 123]);
257 }
258
259 #[test]
260 fn circles_hit_circles() {
261 let mut grid = Grid::new(Vec2::splat(100.0), 10.0);
262 grid.insert(0, circle(50.0, 50.0, 10.0));
263 grid.insert(1, circle(60.0, 60.0, 15.0));
264 grid.insert(2, circle(-10.0, 110.0, 20.0));
265
266 let any = |shape| grid.any(&shape, |_| true);
267 assert!(any(circle(55.0, 55.0, 2.0)));
268 assert!(!any(circle(10.0, 10.0, 10.0)));
269 assert!(any(circle(0.0, 100.0, 10.0)));
270 assert!(any(circle(80.0, 60.0, 10.0)));
271 }
272
273 #[test]
274 fn boxes_hit_circles() {
275 let mut grid = Grid::new(Vec2::splat(100.0), 10.0);
276 grid.insert(0, circle(50.0, 50.0, 10.0));
277 grid.insert(1, circle(60.0, 60.0, 15.0));
278 grid.insert(2, circle(-10.0, 110.0, 20.0));
279
280 assert_eq!(query(&grid, aabb(45.0, 45.0, 55.0, 55.0)), [0, 1]);
281 assert_eq!(query(&grid, aabb(0.0, 0.0, 30.0, 30.0)), [0i16; 0]);
282 assert_eq!(query(&grid, aabb(0.0, 80.0, 20.0, 100.0)), [2]);
283 }
284
285 #[test]
286 fn any_skips_rejected_values() {
287 let mut grid = Grid::new(Vec2::splat(100.0), 10.0);
288 grid.insert(0, aabb(0.0, 0.0, 50.0, 50.0));
289 grid.insert(1, circle(30.0, 30.0, 10.0));
290
291 assert!(grid.any(&aabb(25.0, 25.0, 35.0, 35.0), |&value| value == 1));
292 assert!(!grid.any(&aabb(25.0, 25.0, 35.0, 35.0), |&value| value == 2));
293 assert!(grid.any(&aabb(-1.0, -1.0, 101.0, 101.0), |&value| value == 1));
295 assert!(!grid.any(&aabb(-1.0, -1.0, 101.0, 101.0), |&value| value == 2));
296 }
297
298 #[test]
299 fn large_grids_reach_their_last_cell() {
300 let mut grid = Grid::new(Vec2::splat(5000.0), 25.0);
301 grid.insert(0, aabb(4500.0, 4500.0, 4900.0, 4900.0));
302 assert_eq!(query(&grid, aabb(4000.0, 4000.0, 5000.0, 5000.0)), [0]);
303 }
304}