Skip to main content

euv_core/game/algorithms/spatial/
impl.rs

1use super::*;
2
3/// Geometric helpers for axis-aligned 2D bounds `Bounds2D`.
4impl Bounds2D {
5    /// Creates a normalized `Bounds2D` ensuring `min <= max` per axis.
6    ///
7    /// # Arguments
8    ///
9    /// - `Vec2` - First corner coordinate.
10    /// - `Vec2` - Opposite corner coordinate.
11    ///
12    /// # Returns
13    ///
14    /// - `Self` - Normalized axis-aligned 2D rectangle.
15    #[must_use]
16    pub fn new(corner_a: Vec2, corner_b: Vec2) -> Self {
17        let min_x: f32 = corner_a.get_x().min(corner_b.get_x());
18        let min_y: f32 = corner_a.get_y().min(corner_b.get_y());
19        let max_x: f32 = corner_a.get_x().max(corner_b.get_x());
20        let max_y: f32 = corner_a.get_y().max(corner_b.get_y());
21        Self {
22            min: Vec2::new(min_x, min_y),
23            max: Vec2::new(max_x, max_y),
24        }
25    }
26
27    /// Creates a `Bounds2D` centered at `center` with positive `half_extents`.
28    ///
29    /// # Arguments
30    ///
31    /// - `Vec2` - Center point.
32    /// - `Vec2` - Half-width and half-height extents.
33    ///
34    /// # Returns
35    ///
36    /// - `Self` - Axis-aligned 2D rectangle.
37    #[must_use]
38    pub fn from_center_half(center: Vec2, half_extents: Vec2) -> Self {
39        let hx: f32 = half_extents.get_x().abs();
40        let hy: f32 = half_extents.get_y().abs();
41        Self {
42            min: Vec2::new(center.get_x() - hx, center.get_y() - hy),
43            max: Vec2::new(center.get_x() + hx, center.get_y() + hy),
44        }
45    }
46
47    /// Returns the geometric center of this rectangle.
48    ///
49    /// # Returns
50    ///
51    /// - `Vec2` - Center coordinates.
52    #[must_use]
53    pub fn center(&self) -> Vec2 {
54        Vec2::new(
55            (self.get_min().get_x() + self.get_max().get_x()) * 0.5,
56            (self.get_min().get_y() + self.get_max().get_y()) * 0.5,
57        )
58    }
59
60    /// Returns width and height `(max - min)` of this rectangle.
61    ///
62    /// # Returns
63    ///
64    /// - `Vec2` - Rectangle size vector.
65    #[must_use]
66    pub fn size(&self) -> Vec2 {
67        Vec2::new(
68            self.get_max().get_x() - self.get_min().get_x(),
69            self.get_max().get_y() - self.get_min().get_y(),
70        )
71    }
72
73    /// Tests whether `point` lies inside or on the boundary of this rectangle.
74    ///
75    /// # Arguments
76    ///
77    /// - `Vec2` - Query 2D point.
78    ///
79    /// # Returns
80    ///
81    /// - `bool` - `true` when contained inclusively.
82    #[must_use]
83    pub fn contains_point(&self, point: Vec2) -> bool {
84        let mn: Vec2 = self.get_min();
85        let mx: Vec2 = self.get_max();
86        point.get_x() >= mn.get_x()
87            && point.get_x() <= mx.get_x()
88            && point.get_y() >= mn.get_y()
89            && point.get_y() <= mx.get_y()
90    }
91
92    /// Tests whether this rectangle overlaps `other` inclusively.
93    ///
94    /// # Arguments
95    ///
96    /// - `Self` - Other 2D rectangle.
97    ///
98    /// # Returns
99    ///
100    /// - `bool` - `true` when overlapping.
101    #[must_use]
102    pub fn intersects(&self, other: Self) -> bool {
103        let lmin: Vec2 = self.get_min();
104        let lmax: Vec2 = self.get_max();
105        let rmin: Vec2 = other.get_min();
106        let rmax: Vec2 = other.get_max();
107        lmin.get_x() <= rmax.get_x()
108            && lmax.get_x() >= rmin.get_x()
109            && lmin.get_y() <= rmax.get_y()
110            && lmax.get_y() >= rmin.get_y()
111    }
112
113    /// Computes squared minimum Euclidean distance from `point` to this rectangle.
114    ///
115    /// # Arguments
116    ///
117    /// - `Vec2` - Query 2D point.
118    ///
119    /// # Returns
120    ///
121    /// - `f32` - Zero inside the rectangle, or squared distance to its nearest edge/corner.
122    #[must_use]
123    pub fn min_dist_sq_to_point(&self, point: Vec2) -> f32 {
124        let mn: Vec2 = self.get_min();
125        let mx: Vec2 = self.get_max();
126        let cx: f32 = point.get_x().clamp(mn.get_x(), mx.get_x());
127        let cy: f32 = point.get_y().clamp(mn.get_y(), mx.get_y());
128        let dx: f32 = point.get_x() - cx;
129        let dy: f32 = point.get_y() - cy;
130        dx * dx + dy * dy
131    }
132
133    /// Tests whether this rectangle overlaps a closed circle `(center, radius)`.
134    ///
135    /// # Arguments
136    ///
137    /// - `Vec2` - Circle center.
138    /// - `f32` - Circle radius.
139    ///
140    /// # Returns
141    ///
142    /// - `bool` - `true` when overlapping.
143    #[must_use]
144    pub fn intersects_circle(&self, center: Vec2, radius: f32) -> bool {
145        if !radius.is_finite() || radius < 0.0 {
146            return false;
147        }
148        self.min_dist_sq_to_point(center) <= radius * radius
149    }
150}
151
152/// Default subdivision configuration for `QuadtreeConfig`.
153impl Default for QuadtreeConfig {
154    /// Returns balanced leaf capacity (`8`) and maximum depth (`10`).
155    ///
156    /// # Returns
157    ///
158    /// - `Self` - Default quadtree settings.
159    fn default() -> Self {
160        Self {
161            max_leaf_items: DEFAULT_TREE_LEAF_CAPACITY,
162            max_depth: DEFAULT_QUADTREE_MAX_DEPTH,
163        }
164    }
165}
166
167/// Dynamic insertion, update, removal, and spatial queries for `Quadtree2D`.
168impl Quadtree2D {
169    /// Creates an empty `Quadtree2D` spanning `root_bounds`.
170    ///
171    /// # Arguments
172    ///
173    /// - `Bounds2D` - World-space root bounds.
174    /// - `QuadtreeConfig` - Leaf capacity and depth parameters.
175    ///
176    /// # Returns
177    ///
178    /// - `Self` - Empty adaptive 2D quadtree.
179    #[must_use]
180    pub fn new(root_bounds: Bounds2D, config: QuadtreeConfig) -> Self {
181        let safe_config: QuadtreeConfig = QuadtreeConfig::new(
182            config.get_max_leaf_items().max(1),
183            config.get_max_depth().max(1),
184        );
185        let root: QuadtreeNode2D = QuadtreeNode2D {
186            bounds: root_bounds,
187            depth: 0,
188            children: [SPATIAL_EMPTY_SLOT; 4],
189            items: Vec::with_capacity(safe_config.get_max_leaf_items()),
190        };
191        Self {
192            root_bounds,
193            config: safe_config,
194            nodes: vec![root],
195            positions: HashMap::new(),
196            scratch: QuadtreeScratch::default(),
197        }
198    }
199
200    /// Returns the total number of indexed items currently stored in this quadtree.
201    ///
202    /// # Returns
203    ///
204    /// - `usize` - Number of stored items.
205    #[must_use]
206    pub fn len(&self) -> usize {
207        self.get_positions().len()
208    }
209
210    /// Returns `true` when the quadtree contains no items.
211    ///
212    /// # Returns
213    ///
214    /// - `bool` - Whether the quadtree is empty.
215    #[must_use]
216    pub fn is_empty(&self) -> bool {
217        self.get_positions().is_empty()
218    }
219
220    /// Removes all items and resets the tree to a single empty root node.
221    pub fn clear(&mut self) {
222        let root_bounds: Bounds2D = self.get_root_bounds();
223        let cap: usize = self.get_config().get_max_leaf_items();
224        let nodes: &mut Vec<QuadtreeNode2D> = self.get_mut_nodes();
225        nodes.clear();
226        nodes.push(QuadtreeNode2D {
227            bounds: root_bounds,
228            depth: 0,
229            children: [SPATIAL_EMPTY_SLOT; 4],
230            items: Vec::with_capacity(cap),
231        });
232        self.get_mut_positions().clear();
233    }
234
235    /// Computes child quadrant index `0..4` for `point` relative to `bounds` center.
236    ///
237    /// # Arguments
238    ///
239    /// - `Bounds2D` - Parent node bounds.
240    /// - `Vec2` - Point inside `bounds`.
241    ///
242    /// # Returns
243    ///
244    /// - `usize` - Quadrant index (`0`=SW, `1`=SE, `2`=NW, `3`=NE).
245    fn quadrant_index(bounds: Bounds2D, point: Vec2) -> usize {
246        let center: Vec2 = bounds.center();
247        let east: usize = usize::from(point.get_x() >= center.get_x());
248        let north: usize = usize::from(point.get_y() >= center.get_y());
249        (north << 1) | east
250    }
251
252    /// Computes the bounding rectangle of child quadrant `quad_idx` within `bounds`.
253    ///
254    /// # Arguments
255    ///
256    /// - `Bounds2D` - Parent node bounds.
257    /// - `usize` - Quadrant index in `0..4`.
258    ///
259    /// # Returns
260    ///
261    /// - `Bounds2D` - Sub-quadrant bounding rectangle.
262    fn quadrant_bounds(bounds: Bounds2D, quad_idx: usize) -> Bounds2D {
263        let mn: Vec2 = bounds.get_min();
264        let mx: Vec2 = bounds.get_max();
265        let center: Vec2 = bounds.center();
266        let (x0, x1): (f32, f32) = if (quad_idx & 1) == 0 {
267            (mn.get_x(), center.get_x())
268        } else {
269            (center.get_x(), mx.get_x())
270        };
271        let (y0, y1): (f32, f32) = if (quad_idx & 2) == 0 {
272            (mn.get_y(), center.get_y())
273        } else {
274            (center.get_y(), mx.get_y())
275        };
276        Bounds2D::new(Vec2::new(x0, y0), Vec2::new(x1, y1))
277    }
278
279    /// Subdivides leaf `node_idx` into four children and redistributes its items.
280    ///
281    /// # Arguments
282    ///
283    /// - `&mut Vec<QuadtreeNode2D>` - Node arena.
284    /// - `usize` - Leaf node index to subdivide.
285    /// - `usize` - Initial item capacity for newly created leaf nodes.
286    fn subdivide_node(nodes: &mut Vec<QuadtreeNode2D>, node_idx: usize, leaf_cap: usize) {
287        let parent_bounds: Bounds2D = nodes[node_idx].bounds;
288        let next_depth: usize = nodes[node_idx].depth + 1;
289        let base_idx: usize = nodes.len();
290        let mut child_indices: [usize; 4] = [SPATIAL_EMPTY_SLOT; 4];
291        for (q, slot) in child_indices.iter_mut().enumerate() {
292            *slot = base_idx + q;
293            nodes.push(QuadtreeNode2D {
294                bounds: Self::quadrant_bounds(parent_bounds, q),
295                depth: next_depth,
296                children: [SPATIAL_EMPTY_SLOT; 4],
297                items: Vec::with_capacity(leaf_cap),
298            });
299        }
300        let existing: Vec<SpatialItem2D> = take(&mut nodes[node_idx].items);
301        nodes[node_idx].children = child_indices;
302        for item in existing {
303            let quad: usize = Self::quadrant_index(parent_bounds, item.get_position());
304            nodes[child_indices[quad]].items.push(item);
305        }
306    }
307
308    /// Inserts `item` into the node arena starting at `root_idx`.
309    ///
310    /// # Arguments
311    ///
312    /// - `&mut Vec<QuadtreeNode2D>` - Node arena.
313    /// - `usize` - Starting node index.
314    /// - `SpatialItem2D` - Item to insert.
315    /// - `QuadtreeConfig` - Subdivision parameters.
316    fn insert_into_nodes(
317        nodes: &mut Vec<QuadtreeNode2D>,
318        mut node_idx: usize,
319        item: SpatialItem2D,
320        config: QuadtreeConfig,
321    ) {
322        loop {
323            if nodes[node_idx].children[0] != SPATIAL_EMPTY_SLOT {
324                let quad: usize = Self::quadrant_index(nodes[node_idx].bounds, item.get_position());
325                node_idx = nodes[node_idx].children[quad];
326                continue;
327            }
328            if nodes[node_idx].items.len() >= config.get_max_leaf_items()
329                && nodes[node_idx].depth < config.get_max_depth()
330            {
331                Self::subdivide_node(nodes, node_idx, config.get_max_leaf_items());
332                let quad: usize = Self::quadrant_index(nodes[node_idx].bounds, item.get_position());
333                node_idx = nodes[node_idx].children[quad];
334                continue;
335            }
336            nodes[node_idx].items.push(item);
337            break;
338        }
339    }
340
341    /// Inserts or updates an item `(id, position)`; returns `false` if `position` is outside root bounds or non-finite.
342    ///
343    /// # Arguments
344    ///
345    /// - `u64` - Unique item identifier.
346    /// - `Vec2` - World-space 2D position.
347    ///
348    /// # Returns
349    ///
350    /// - `bool` - `true` when inserted or updated inside root bounds.
351    pub fn insert(&mut self, id: u64, position: Vec2) -> bool {
352        if !position.get_x().is_finite()
353            || !position.get_y().is_finite()
354            || !self.get_root_bounds().contains_point(position)
355        {
356            return false;
357        }
358        if self.get_positions().contains_key(&id) {
359            return self.update(id, position);
360        }
361        let cfg: QuadtreeConfig = self.get_config();
362        let item: SpatialItem2D = SpatialItem2D::new(id, position);
363        Self::insert_into_nodes(self.get_mut_nodes(), 0, item, cfg);
364        let _: Option<Vec2> = self.get_mut_positions().insert(id, position);
365        true
366    }
367
368    /// Removes the item with identifier `id` from the quadtree.
369    ///
370    /// # Arguments
371    ///
372    /// - `u64` - Item identifier to remove.
373    ///
374    /// # Returns
375    ///
376    /// - `bool` - `true` if the item existed and was removed.
377    pub fn remove(&mut self, id: u64) -> bool {
378        let Some(old_pos) = self.get_mut_positions().remove(&id) else {
379            return false;
380        };
381        let nodes: &mut Vec<QuadtreeNode2D> = self.get_mut_nodes();
382        let mut node_idx: usize = 0;
383        loop {
384            if nodes[node_idx].children[0] != SPATIAL_EMPTY_SLOT {
385                let quad: usize = Self::quadrant_index(nodes[node_idx].bounds, old_pos);
386                node_idx = nodes[node_idx].children[quad];
387                continue;
388            }
389            if let Some(pos_idx) = nodes[node_idx]
390                .items
391                .iter()
392                .position(|entry: &SpatialItem2D| entry.get_id() == id)
393            {
394                let _: SpatialItem2D = nodes[node_idx].items.swap_remove(pos_idx);
395            }
396            break;
397        }
398        true
399    }
400
401    /// Moves an existing item `id` to `new_position`, updating in place when remaining in the same leaf.
402    ///
403    /// # Arguments
404    ///
405    /// - `u64` - Existing item identifier.
406    /// - `Vec2` - New world-space 2D position.
407    ///
408    /// # Returns
409    ///
410    /// - `bool` - `true` when `id` existed and `new_position` lies inside root bounds.
411    pub fn update(&mut self, id: u64, new_position: Vec2) -> bool {
412        if !new_position.get_x().is_finite()
413            || !new_position.get_y().is_finite()
414            || !self.get_root_bounds().contains_point(new_position)
415        {
416            return false;
417        }
418        let Some(&old_pos) = self.get_positions().get(&id) else {
419            return false;
420        };
421        let mut leaf_idx: usize = 0;
422        let nodes: &mut Vec<QuadtreeNode2D> = self.get_mut_nodes();
423        while nodes[leaf_idx].children[0] != SPATIAL_EMPTY_SLOT {
424            let quad: usize = Self::quadrant_index(nodes[leaf_idx].bounds, old_pos);
425            leaf_idx = nodes[leaf_idx].children[quad];
426        }
427        if nodes[leaf_idx].bounds.contains_point(new_position) {
428            if let Some(entry) = nodes[leaf_idx]
429                .items
430                .iter_mut()
431                .find(|entry: &&mut SpatialItem2D| entry.get_id() == id)
432            {
433                entry.set_position(new_position);
434            }
435            let _: Option<Vec2> = self.get_mut_positions().insert(id, new_position);
436            return true;
437        }
438        let _: bool = self.remove(id);
439        self.insert(id, new_position)
440    }
441
442    /// Recursively collects all item IDs inside `query_bounds`.
443    ///
444    /// # Arguments
445    ///
446    /// - `&[QuadtreeNode2D]` - Node arena slice.
447    /// - `usize` - Current node index.
448    /// - `Bounds2D` - Query rectangle.
449    /// - `&mut Vec<u64>` - Output ID buffer.
450    fn query_rect_rec(
451        nodes: &[QuadtreeNode2D],
452        node_idx: usize,
453        query_bounds: Bounds2D,
454        out: &mut Vec<u64>,
455    ) {
456        let node: &QuadtreeNode2D = &nodes[node_idx];
457        if !node.bounds.intersects(query_bounds) {
458            return;
459        }
460        if node.children[0] != SPATIAL_EMPTY_SLOT {
461            for &child in &node.children {
462                Self::query_rect_rec(nodes, child, query_bounds, out);
463            }
464            return;
465        }
466        for item in &node.items {
467            if query_bounds.contains_point(item.get_position()) {
468                out.push(item.get_id());
469            }
470        }
471    }
472
473    /// Queries all items whose positions lie inside `query_bounds`, writing IDs into `out`.
474    ///
475    /// # Arguments
476    ///
477    /// - `Bounds2D` - Axis-aligned query rectangle.
478    /// - `&mut Vec<u64>` - Reusable output identifier buffer (cleared first).
479    pub fn query_rect(&self, query_bounds: Bounds2D, out: &mut Vec<u64>) {
480        out.clear();
481        if self.get_nodes().is_empty() {
482            return;
483        }
484        Self::query_rect_rec(self.get_nodes(), 0, query_bounds, out);
485    }
486
487    /// Recursively collects all item IDs within closed circle `(center, radius)`.
488    ///
489    /// # Arguments
490    ///
491    /// - `&[QuadtreeNode2D]` - Node arena slice.
492    /// - `usize` - Current node index.
493    /// - `Vec2` - Query circle center.
494    /// - `f32` - Query circle radius.
495    /// - `f32` - Precomputed squared radius.
496    /// - `&mut Vec<u64>` - Output ID buffer.
497    fn query_radius_rec(
498        nodes: &[QuadtreeNode2D],
499        node_idx: usize,
500        center: Vec2,
501        radius: f32,
502        radius_sq: f32,
503        out: &mut Vec<u64>,
504    ) {
505        let node: &QuadtreeNode2D = &nodes[node_idx];
506        if !node.bounds.intersects_circle(center, radius) {
507            return;
508        }
509        if node.children[0] != SPATIAL_EMPTY_SLOT {
510            for &child in &node.children {
511                Self::query_radius_rec(nodes, child, center, radius, radius_sq, out);
512            }
513            return;
514        }
515        for item in &node.items {
516            if spatial_dist_sq_2d(item.get_position(), center) <= radius_sq {
517                out.push(item.get_id());
518            }
519        }
520    }
521
522    /// Queries all items within Euclidean distance `<= radius` of `center`, writing IDs into `out`.
523    ///
524    /// # Arguments
525    ///
526    /// - `Vec2` - Query circle center.
527    /// - `f32` - Query radius (non-negative).
528    /// - `&mut Vec<u64>` - Reusable output identifier buffer (cleared first).
529    pub fn query_radius(&self, center: Vec2, radius: f32, out: &mut Vec<u64>) {
530        out.clear();
531        let valid_radius: bool = radius.is_finite() && radius >= 0.0;
532        if !valid_radius || self.get_nodes().is_empty() {
533            return;
534        }
535        Self::query_radius_rec(self.get_nodes(), 0, center, radius, radius * radius, out);
536    }
537
538    /// Finds the exact `k` nearest items to `center` using best-first branch-and-bound traversal.
539    ///
540    /// # Arguments
541    ///
542    /// - `Vec2` - Query center point.
543    /// - `usize` - Maximum number of nearest neighbors to return.
544    /// - `&mut Vec<(u64, f32)>` - Reusable output receiving `(id, euclidean_distance)` sorted ascending.
545    pub fn query_k_nearest(&mut self, center: Vec2, k: usize, out: &mut Vec<(u64, f32)>) {
546        out.clear();
547        if k == 0 || self.get_nodes().is_empty() || self.is_empty() {
548            return;
549        }
550        let mut scratch: QuadtreeScratch = take(self.get_mut_scratch());
551        scratch.node_heap.clear();
552        scratch.best_items.clear();
553        let nodes: &[QuadtreeNode2D] = self.get_nodes();
554        let root_dist_sq: f32 = nodes[0].bounds.min_dist_sq_to_point(center);
555        spatial_heap_push(&mut scratch.node_heap, root_dist_sq, 0);
556        while let Some((node_dist_sq, node_idx)) = spatial_heap_pop(&mut scratch.node_heap) {
557            if scratch.best_items.len() == k
558                && let Some(&(worst_sq, _)) = scratch.best_items.last()
559                && node_dist_sq > worst_sq
560            {
561                break;
562            }
563            let node: &QuadtreeNode2D = &nodes[node_idx];
564            if node.children[0] != SPATIAL_EMPTY_SLOT {
565                for &child in &node.children {
566                    let child_dist_sq: f32 = nodes[child].bounds.min_dist_sq_to_point(center);
567                    let prune: bool = if scratch.best_items.len() == k {
568                        scratch
569                            .best_items
570                            .last()
571                            .is_some_and(|&(worst_sq, _): &(f32, u64)| child_dist_sq > worst_sq)
572                    } else {
573                        false
574                    };
575                    if !prune {
576                        spatial_heap_push(&mut scratch.node_heap, child_dist_sq, child);
577                    }
578                }
579            } else {
580                for item in &node.items {
581                    let d_sq: f32 = spatial_dist_sq_2d(item.get_position(), center);
582                    let id: u64 = item.get_id();
583                    if scratch.best_items.len() < k {
584                        scratch.best_items.push((d_sq, id));
585                        scratch
586                            .best_items
587                            .sort_by(|lhs: &(f32, u64), rhs: &(f32, u64)| {
588                                lhs.0.total_cmp(&rhs.0).then_with(|| lhs.1.cmp(&rhs.1))
589                            });
590                    } else if let Some(&(worst_sq, worst_id)) = scratch.best_items.last()
591                        && (d_sq < worst_sq || (d_sq == worst_sq && id < worst_id))
592                    {
593                        let last_slot: usize = scratch.best_items.len() - 1;
594                        scratch.best_items[last_slot] = (d_sq, id);
595                        scratch
596                            .best_items
597                            .sort_by(|lhs: &(f32, u64), rhs: &(f32, u64)| {
598                                lhs.0.total_cmp(&rhs.0).then_with(|| lhs.1.cmp(&rhs.1))
599                            });
600                    }
601                }
602            }
603        }
604        for &(d_sq, id) in &scratch.best_items {
605            out.push((id, d_sq.sqrt()));
606        }
607        self.set_scratch(scratch);
608    }
609}
610
611/// Default subdivision configuration for `OctreeConfig`.
612impl Default for OctreeConfig {
613    /// Returns balanced leaf capacity (`8`) and maximum depth (`8`).
614    ///
615    /// # Returns
616    ///
617    /// - `Self` - Default octree settings.
618    fn default() -> Self {
619        Self {
620            max_leaf_items: DEFAULT_TREE_LEAF_CAPACITY,
621            max_depth: DEFAULT_OCTREE_MAX_DEPTH,
622        }
623    }
624}
625
626/// Dynamic insertion, update, removal, and AABB/sphere/ray queries for `Octree3D`.
627impl Octree3D {
628    /// Creates an empty `Octree3D` spanning `root_bounds`.
629    ///
630    /// # Arguments
631    ///
632    /// - `AxisAlignedBox3D` - World-space root volume.
633    /// - `OctreeConfig` - Leaf capacity and maximum depth parameters.
634    ///
635    /// # Returns
636    ///
637    /// - `Self` - Empty adaptive 3D octree.
638    #[must_use]
639    pub fn new(root_bounds: AxisAlignedBox3D, config: OctreeConfig) -> Self {
640        let safe_config: OctreeConfig = OctreeConfig::new(
641            config.get_max_leaf_items().max(1),
642            config.get_max_depth().max(1),
643        );
644        let root: OctreeNode3D = OctreeNode3D {
645            bounds: root_bounds,
646            depth: 0,
647            children: [SPATIAL_EMPTY_SLOT; 8],
648            items: Vec::with_capacity(safe_config.get_max_leaf_items()),
649        };
650        Self {
651            root_bounds,
652            config: safe_config,
653            nodes: vec![root],
654            item_bounds: HashMap::new(),
655        }
656    }
657
658    /// Returns the number of indexed items stored in this octree.
659    ///
660    /// # Returns
661    ///
662    /// - `usize` - Total stored item count.
663    #[must_use]
664    pub fn len(&self) -> usize {
665        self.get_item_bounds().len()
666    }
667
668    /// Returns `true` when the octree contains no items.
669    ///
670    /// # Returns
671    ///
672    /// - `bool` - Whether empty.
673    #[must_use]
674    pub fn is_empty(&self) -> bool {
675        self.get_item_bounds().is_empty()
676    }
677
678    /// Removes all items and resets the octree to a single empty root node.
679    pub fn clear(&mut self) {
680        let root_bounds: AxisAlignedBox3D = self.get_root_bounds();
681        let cap: usize = self.get_config().get_max_leaf_items();
682        let nodes: &mut Vec<OctreeNode3D> = self.get_mut_nodes();
683        nodes.clear();
684        nodes.push(OctreeNode3D {
685            bounds: root_bounds,
686            depth: 0,
687            children: [SPATIAL_EMPTY_SLOT; 8],
688            items: Vec::with_capacity(cap),
689        });
690        self.get_mut_item_bounds().clear();
691    }
692
693    /// Computes child octant bounds `oct_idx` in `0..8` of `bounds`.
694    ///
695    /// # Arguments
696    ///
697    /// - `AxisAlignedBox3D` - Parent bounding box.
698    /// - `usize` - Octant bitmask index (`bit 0 = +X`, `bit 1 = +Y`, `bit 2 = +Z`).
699    ///
700    /// # Returns
701    ///
702    /// - `AxisAlignedBox3D` - Sub-octant bounding box.
703    fn octant_bounds(bounds: AxisAlignedBox3D, oct_idx: usize) -> AxisAlignedBox3D {
704        let mn: Vec3 = bounds.get_min();
705        let mx: Vec3 = bounds.get_max();
706        let c: Vec3 = bounds.center();
707        let (x0, x1): (f32, f32) = if (oct_idx & 1) == 0 {
708            (mn.get_x(), c.get_x())
709        } else {
710            (c.get_x(), mx.get_x())
711        };
712        let (y0, y1): (f32, f32) = if (oct_idx & 2) == 0 {
713            (mn.get_y(), c.get_y())
714        } else {
715            (c.get_y(), mx.get_y())
716        };
717        let (z0, z1): (f32, f32) = if (oct_idx & 4) == 0 {
718            (mn.get_z(), c.get_z())
719        } else {
720            (c.get_z(), mx.get_z())
721        };
722        AxisAlignedBox3D::new(Vec3::new(x0, y0, z0), Vec3::new(x1, y1, z1))
723    }
724
725    /// Returns the single child octant index that completely encloses `item_box`, if any.
726    ///
727    /// # Arguments
728    ///
729    /// - `&[OctreeNode3D]` - Node arena.
730    /// - `[usize; 8]` - Child node indices.
731    /// - `AxisAlignedBox3D` - Candidate item bounds.
732    ///
733    /// # Returns
734    ///
735    /// - `Option<usize>` - Enclosing child node index, or `None` if `item_box` straddles a split plane.
736    fn enclosing_child(
737        nodes: &[OctreeNode3D],
738        children: [usize; 8],
739        item_box: AxisAlignedBox3D,
740    ) -> Option<usize> {
741        children
742            .iter()
743            .copied()
744            .find(|child: &usize| aabb3d_contains_box(nodes[*child].bounds, item_box))
745    }
746
747    /// Subdivides `node_idx` into eight octants and pushes enclosed items into matching children.
748    ///
749    /// # Arguments
750    ///
751    /// - `&mut Vec<OctreeNode3D>` - Node arena.
752    /// - `usize` - Node index to subdivide.
753    /// - `usize` - Leaf item capacity hint.
754    fn subdivide_node(nodes: &mut Vec<OctreeNode3D>, node_idx: usize, leaf_cap: usize) {
755        let parent_bounds: AxisAlignedBox3D = nodes[node_idx].bounds;
756        let next_depth: usize = nodes[node_idx].depth + 1;
757        let base_idx: usize = nodes.len();
758        let mut child_indices: [usize; 8] = [SPATIAL_EMPTY_SLOT; 8];
759        for (oct, slot) in child_indices.iter_mut().enumerate() {
760            *slot = base_idx + oct;
761            nodes.push(OctreeNode3D {
762                bounds: Self::octant_bounds(parent_bounds, oct),
763                depth: next_depth,
764                children: [SPATIAL_EMPTY_SLOT; 8],
765                items: Vec::with_capacity(leaf_cap),
766            });
767        }
768        let existing: Vec<SpatialItem3D> = take(&mut nodes[node_idx].items);
769        nodes[node_idx].children = child_indices;
770        let mut straddling: Vec<SpatialItem3D> = Vec::new();
771        for item in existing {
772            if let Some(child_idx) = Self::enclosing_child(nodes, child_indices, item.get_bounds())
773            {
774                nodes[child_idx].items.push(item);
775            } else {
776                straddling.push(item);
777            }
778        }
779        nodes[node_idx].items = straddling;
780    }
781
782    /// Inserts `item` into the octree node arena.
783    ///
784    /// # Arguments
785    ///
786    /// - `&mut Vec<OctreeNode3D>` - Node arena.
787    /// - `usize` - Starting node index.
788    /// - `SpatialItem3D` - Item to insert.
789    /// - `OctreeConfig` - Subdivision configuration.
790    fn insert_into_nodes(
791        nodes: &mut Vec<OctreeNode3D>,
792        mut node_idx: usize,
793        item: SpatialItem3D,
794        config: OctreeConfig,
795    ) {
796        loop {
797            if nodes[node_idx].children[0] != SPATIAL_EMPTY_SLOT {
798                let children: [usize; 8] = nodes[node_idx].children;
799                if let Some(child_idx) = Self::enclosing_child(nodes, children, item.get_bounds()) {
800                    node_idx = child_idx;
801                    continue;
802                }
803                nodes[node_idx].items.push(item);
804                break;
805            }
806            if nodes[node_idx].items.len() >= config.get_max_leaf_items()
807                && nodes[node_idx].depth < config.get_max_depth()
808            {
809                Self::subdivide_node(nodes, node_idx, config.get_max_leaf_items());
810                let children: [usize; 8] = nodes[node_idx].children;
811                if let Some(child_idx) = Self::enclosing_child(nodes, children, item.get_bounds()) {
812                    node_idx = child_idx;
813                    continue;
814                }
815                nodes[node_idx].items.push(item);
816                break;
817            }
818            nodes[node_idx].items.push(item);
819            break;
820        }
821    }
822
823    /// Inserts or updates a 3D bounding-box item; returns `false` if outside root bounds.
824    ///
825    /// # Arguments
826    ///
827    /// - `u64` - Unique item identifier.
828    /// - `AxisAlignedBox3D` - Item axis-aligned bounding box.
829    ///
830    /// # Returns
831    ///
832    /// - `bool` - `true` when indexed inside root bounds.
833    pub fn insert(&mut self, id: u64, bounds: AxisAlignedBox3D) -> bool {
834        let norm: AxisAlignedBox3D = AxisAlignedBox3D::new(
835            bounds.get_min().min(bounds.get_max()),
836            bounds.get_min().max(bounds.get_max()),
837        );
838        if !aabb3d_contains_box(self.get_root_bounds(), norm) {
839            return false;
840        }
841        if self.get_item_bounds().contains_key(&id) {
842            let _: bool = self.remove(id);
843        }
844        let cfg: OctreeConfig = self.get_config();
845        Self::insert_into_nodes(self.get_mut_nodes(), 0, SpatialItem3D::new(id, norm), cfg);
846        let _: Option<AxisAlignedBox3D> = self.get_mut_item_bounds().insert(id, norm);
847        true
848    }
849
850    /// Inserts a point item as a zero-volume `AxisAlignedBox3D` at `position`.
851    ///
852    /// # Arguments
853    ///
854    /// - `u64` - Unique item identifier.
855    /// - `Vec3` - World-space 3D position.
856    ///
857    /// # Returns
858    ///
859    /// - `bool` - `true` when indexed inside root bounds.
860    pub fn insert_point(&mut self, id: u64, position: Vec3) -> bool {
861        self.insert(id, AxisAlignedBox3D::new(position, position))
862    }
863
864    /// Removes item `id` from the octree.
865    ///
866    /// # Arguments
867    ///
868    /// - `u64` - Item identifier to remove.
869    ///
870    /// # Returns
871    ///
872    /// - `bool` - `true` when present and removed.
873    pub fn remove(&mut self, id: u64) -> bool {
874        let Some(old_bounds) = self.get_mut_item_bounds().remove(&id) else {
875            return false;
876        };
877        let nodes: &mut Vec<OctreeNode3D> = self.get_mut_nodes();
878        let mut node_idx: usize = 0;
879        loop {
880            if let Some(pos) = nodes[node_idx]
881                .items
882                .iter()
883                .position(|entry: &SpatialItem3D| entry.get_id() == id)
884            {
885                let _: SpatialItem3D = nodes[node_idx].items.swap_remove(pos);
886                return true;
887            }
888            if nodes[node_idx].children[0] == SPATIAL_EMPTY_SLOT {
889                break;
890            }
891            let children: [usize; 8] = nodes[node_idx].children;
892            if let Some(child_idx) = Self::enclosing_child(nodes, children, old_bounds) {
893                node_idx = child_idx;
894            } else {
895                break;
896            }
897        }
898        true
899    }
900
901    /// Updates an existing item's bounding box in the octree.
902    ///
903    /// # Arguments
904    ///
905    /// - `u64` - Existing item identifier.
906    /// - `AxisAlignedBox3D` - Updated 3D bounding box.
907    ///
908    /// # Returns
909    ///
910    /// - `bool` - `true` when `id` existed and `new_bounds` lies inside root bounds.
911    pub fn update(&mut self, id: u64, new_bounds: AxisAlignedBox3D) -> bool {
912        if !self.get_item_bounds().contains_key(&id) {
913            return false;
914        }
915        self.insert(id, new_bounds)
916    }
917
918    /// Recursively collects all item IDs overlapping `query_box`.
919    ///
920    /// # Arguments
921    ///
922    /// - `&[OctreeNode3D]` - Node arena slice.
923    /// - `usize` - Active node index.
924    /// - `AxisAlignedBox3D` - Query volume.
925    /// - `&mut Vec<u64>` - Output ID buffer.
926    fn query_aabb_rec(
927        nodes: &[OctreeNode3D],
928        node_idx: usize,
929        query_box: AxisAlignedBox3D,
930        out: &mut Vec<u64>,
931    ) {
932        let node: &OctreeNode3D = &nodes[node_idx];
933        if !aabb3d_intersects(node.bounds, query_box) {
934            return;
935        }
936        for item in &node.items {
937            if aabb3d_intersects(item.get_bounds(), query_box) {
938                out.push(item.get_id());
939            }
940        }
941        if node.children[0] != SPATIAL_EMPTY_SLOT {
942            for &child in &node.children {
943                Self::query_aabb_rec(nodes, child, query_box, out);
944            }
945        }
946    }
947
948    /// Queries all items overlapping `query_box`, writing matching IDs into `out`.
949    ///
950    /// # Arguments
951    ///
952    /// - `AxisAlignedBox3D` - Query bounding box.
953    /// - `&mut Vec<u64>` - Reusable output buffer (cleared first).
954    pub fn query_aabb(&self, query_box: AxisAlignedBox3D, out: &mut Vec<u64>) {
955        out.clear();
956        if self.get_nodes().is_empty() {
957            return;
958        }
959        Self::query_aabb_rec(self.get_nodes(), 0, query_box, out);
960    }
961
962    /// Recursively collects all item IDs intersecting sphere `(center, radius)`.
963    ///
964    /// # Arguments
965    ///
966    /// - `&[OctreeNode3D]` - Node arena slice.
967    /// - `usize` - Active node index.
968    /// - `Vec3` - Sphere center.
969    /// - `f32` - Sphere radius.
970    /// - `&mut Vec<u64>` - Output ID buffer.
971    fn query_sphere_rec(
972        nodes: &[OctreeNode3D],
973        node_idx: usize,
974        center: Vec3,
975        radius: f32,
976        out: &mut Vec<u64>,
977    ) {
978        let node: &OctreeNode3D = &nodes[node_idx];
979        if !aabb3d_intersects_sphere(node.bounds, center, radius) {
980            return;
981        }
982        for item in &node.items {
983            if aabb3d_intersects_sphere(item.get_bounds(), center, radius) {
984                out.push(item.get_id());
985            }
986        }
987        if node.children[0] != SPATIAL_EMPTY_SLOT {
988            for &child in &node.children {
989                Self::query_sphere_rec(nodes, child, center, radius, out);
990            }
991        }
992    }
993
994    /// Queries all items intersecting sphere `(center, radius)`, writing IDs into `out`.
995    ///
996    /// # Arguments
997    ///
998    /// - `Vec3` - Query sphere center.
999    /// - `f32` - Query sphere radius.
1000    /// - `&mut Vec<u64>` - Reusable output buffer (cleared first).
1001    pub fn query_sphere(&self, center: Vec3, radius: f32, out: &mut Vec<u64>) {
1002        out.clear();
1003        let valid_radius: bool = radius.is_finite() && radius >= 0.0;
1004        if !valid_radius || self.get_nodes().is_empty() {
1005            return;
1006        }
1007        Self::query_sphere_rec(self.get_nodes(), 0, center, radius, out);
1008    }
1009
1010    /// Recursively collects all item IDs intersected by `ray` within `[0.0, max_distance]`.
1011    ///
1012    /// # Arguments
1013    ///
1014    /// - `&[OctreeNode3D]` - Node arena slice.
1015    /// - `usize` - Active node index.
1016    /// - `&Ray3D` - Query ray.
1017    /// - `f32` - Maximum hit distance.
1018    /// - `&mut Vec<u64>` - Output ID buffer.
1019    fn query_ray_rec(
1020        nodes: &[OctreeNode3D],
1021        node_idx: usize,
1022        ray: &Ray3D,
1023        max_distance: f32,
1024        out: &mut Vec<u64>,
1025    ) {
1026        let node: &OctreeNode3D = &nodes[node_idx];
1027        if !node.bounds.intersects_ray(ray, 0.0, max_distance) {
1028            return;
1029        }
1030        for item in &node.items {
1031            if item.get_bounds().intersects_ray(ray, 0.0, max_distance) {
1032                out.push(item.get_id());
1033            }
1034        }
1035        if node.children[0] != SPATIAL_EMPTY_SLOT {
1036            for &child in &node.children {
1037                Self::query_ray_rec(nodes, child, ray, max_distance, out);
1038            }
1039        }
1040    }
1041
1042    /// Queries all items intersected by `ray` within `[0.0, max_distance]`, writing IDs into `out`.
1043    ///
1044    /// # Arguments
1045    ///
1046    /// - `Ray3D` - 3D ray with precomputed reciprocal direction.
1047    /// - `f32` - Maximum valid ray distance.
1048    /// - `&mut Vec<u64>` - Reusable output buffer (cleared first).
1049    pub fn query_ray(&self, ray: Ray3D, max_distance: f32, out: &mut Vec<u64>) {
1050        out.clear();
1051        let valid_dist: bool = max_distance.is_finite() && max_distance >= 0.0;
1052        if !valid_dist || self.get_nodes().is_empty() {
1053            return;
1054        }
1055        Self::query_ray_rec(self.get_nodes(), 0, &ray, max_distance, out);
1056    }
1057}
1058
1059/// Zero-allocation open-addressed uniform-cell 2D spatial hash grid operations.
1060impl SpatialHashGrid2D {
1061    /// Creates an empty `SpatialHashGrid2D` with uniform `cell_size`.
1062    ///
1063    /// # Arguments
1064    ///
1065    /// - `f32` - Cell edge length (clamped to `>= 1e-4`).
1066    ///
1067    /// # Returns
1068    ///
1069    /// - `Self` - Pre-allocated 2D spatial hash grid.
1070    #[must_use]
1071    pub fn new(cell_size: f32) -> Self {
1072        let safe_size: f32 = if cell_size.is_finite() && cell_size > 1e-4 {
1073            cell_size
1074        } else {
1075            1.0
1076        };
1077        Self {
1078            cell_size: safe_size,
1079            inv_cell_size: 1.0 / safe_size,
1080            occupied_buckets: 0,
1081            buckets: vec![
1082                SpatialHashBucket2D {
1083                    cx: 0,
1084                    cy: 0,
1085                    head: SPATIAL_EMPTY_SLOT,
1086                };
1087                SPATIAL_HASH_INIT_CAP
1088            ],
1089            touched_buckets: Vec::with_capacity(SPATIAL_HASH_INIT_CAP / 2),
1090            entries: Vec::with_capacity(SPATIAL_HASH_INIT_CAP),
1091            query_scratch: Vec::with_capacity(64),
1092        }
1093    }
1094
1095    /// Clears all entries in O(active_cells) time while retaining every internal buffer's capacity.
1096    pub fn clear(&mut self) {
1097        let mut touched: Vec<usize> = take(self.get_mut_touched_buckets());
1098        let buckets: &mut Vec<SpatialHashBucket2D> = self.get_mut_buckets();
1099        for &slot in &touched {
1100            buckets[slot].head = SPATIAL_EMPTY_SLOT;
1101        }
1102        touched.clear();
1103        self.set_touched_buckets(touched);
1104        self.get_mut_entries().clear();
1105        self.set_occupied_buckets(0);
1106    }
1107
1108    /// Doubles the open-addressed bucket table when load exceeds 65% and rehashes active cells.
1109    fn grow_buckets(&mut self) {
1110        let old_buckets: Vec<SpatialHashBucket2D> = take(self.get_mut_buckets());
1111        let old_touched: Vec<usize> = take(self.get_mut_touched_buckets());
1112        let new_cap: usize = (old_buckets.len() * 2).max(SPATIAL_HASH_INIT_CAP);
1113        let mask: usize = new_cap - 1;
1114        let mut new_buckets: Vec<SpatialHashBucket2D> = vec![
1115            SpatialHashBucket2D {
1116                cx: 0,
1117                cy: 0,
1118                head: SPATIAL_EMPTY_SLOT,
1119            };
1120            new_cap
1121        ];
1122        let mut new_touched: Vec<usize> = Vec::with_capacity(old_touched.len() * 2);
1123        for &old_slot in &old_touched {
1124            let bucket: SpatialHashBucket2D = old_buckets[old_slot];
1125            if bucket.head == SPATIAL_EMPTY_SLOT {
1126                continue;
1127            }
1128            let mut slot: usize = spatial_hash_2d(bucket.cx, bucket.cy) & mask;
1129            while new_buckets[slot].head != SPATIAL_EMPTY_SLOT {
1130                slot = (slot + 1) & mask;
1131            }
1132            new_buckets[slot] = bucket;
1133            new_touched.push(slot);
1134        }
1135        self.set_buckets(new_buckets);
1136        self.set_touched_buckets(new_touched);
1137    }
1138
1139    /// Inserts an item `(id, bounds)` into every cell overlapped by `bounds`.
1140    ///
1141    /// # Arguments
1142    ///
1143    /// - `u64` - Entity identifier.
1144    /// - `Bounds2D` - World-space 2D bounding rectangle.
1145    pub fn insert_bounds(&mut self, id: u64, bounds: Bounds2D) {
1146        let inv: f32 = self.get_inv_cell_size();
1147        let min_cx: i32 = (bounds.get_min().get_x() * inv).floor() as i32;
1148        let max_cx: i32 = (bounds.get_max().get_x() * inv).floor() as i32;
1149        let min_cy: i32 = (bounds.get_min().get_y() * inv).floor() as i32;
1150        let max_cy: i32 = (bounds.get_max().get_y() * inv).floor() as i32;
1151        for cy in min_cy..=max_cy {
1152            for cx in min_cx..=max_cx {
1153                if self.get_occupied_buckets() * 10 >= self.get_buckets().len() * 6 {
1154                    self.grow_buckets();
1155                }
1156                let mask: usize = self.get_buckets().len() - 1;
1157                let mut slot: usize = spatial_hash_2d(cx, cy) & mask;
1158                let mut is_new_bucket: bool = false;
1159                loop {
1160                    let bucket: SpatialHashBucket2D = self.get_buckets()[slot];
1161                    if bucket.head == SPATIAL_EMPTY_SLOT {
1162                        is_new_bucket = true;
1163                        break;
1164                    }
1165                    if bucket.cx == cx && bucket.cy == cy {
1166                        break;
1167                    }
1168                    slot = (slot + 1) & mask;
1169                }
1170                let prev_head: usize = self.get_buckets()[slot].head;
1171                let entry_idx: usize = self.get_entries().len();
1172                self.get_mut_entries().push(SpatialHashEntry2D {
1173                    id,
1174                    bounds,
1175                    next: prev_head,
1176                });
1177                let bucket_mut: &mut SpatialHashBucket2D = &mut self.get_mut_buckets()[slot];
1178                bucket_mut.cx = cx;
1179                bucket_mut.cy = cy;
1180                bucket_mut.head = entry_idx;
1181                if is_new_bucket {
1182                    self.get_mut_touched_buckets().push(slot);
1183                    let next_occ: usize = self.get_occupied_buckets() + 1;
1184                    self.set_occupied_buckets(next_occ);
1185                }
1186            }
1187        }
1188    }
1189
1190    /// Inserts a point item `(id, position)` into its enclosing cell.
1191    ///
1192    /// # Arguments
1193    ///
1194    /// - `u64` - Entity identifier.
1195    /// - `Vec2` - World-space 2D position.
1196    pub fn insert_point(&mut self, id: u64, position: Vec2) {
1197        if !position.get_x().is_finite() || !position.get_y().is_finite() {
1198            return;
1199        }
1200        self.insert_bounds(id, Bounds2D::new(position, position));
1201    }
1202
1203    /// Queries all items overlapping `query_bounds`, writing deduplicated IDs into `out`.
1204    ///
1205    /// # Arguments
1206    ///
1207    /// - `Bounds2D` - Query rectangle.
1208    /// - `&mut Vec<u64>` - Reusable output buffer (cleared and deduplicated).
1209    pub fn query_rect_into(&self, query_bounds: Bounds2D, out: &mut Vec<u64>) {
1210        out.clear();
1211        let inv: f32 = self.get_inv_cell_size();
1212        let min_cx: i32 = (query_bounds.get_min().get_x() * inv).floor() as i32;
1213        let max_cx: i32 = (query_bounds.get_max().get_x() * inv).floor() as i32;
1214        let min_cy: i32 = (query_bounds.get_min().get_y() * inv).floor() as i32;
1215        let max_cy: i32 = (query_bounds.get_max().get_y() * inv).floor() as i32;
1216        let buckets: &[SpatialHashBucket2D] = self.get_buckets();
1217        let entries: &[SpatialHashEntry2D] = self.get_entries();
1218        let mask: usize = buckets.len() - 1;
1219        for cy in min_cy..=max_cy {
1220            for cx in min_cx..=max_cx {
1221                let mut slot: usize = spatial_hash_2d(cx, cy) & mask;
1222                loop {
1223                    let bucket: SpatialHashBucket2D = buckets[slot];
1224                    if bucket.head == SPATIAL_EMPTY_SLOT {
1225                        break;
1226                    }
1227                    if bucket.cx == cx && bucket.cy == cy {
1228                        let mut cursor: usize = bucket.head;
1229                        while cursor != SPATIAL_EMPTY_SLOT {
1230                            let entry: SpatialHashEntry2D = entries[cursor];
1231                            if entry.bounds.intersects(query_bounds) {
1232                                out.push(entry.id);
1233                            }
1234                            cursor = entry.next;
1235                        }
1236                        break;
1237                    }
1238                    slot = (slot + 1) & mask;
1239                }
1240            }
1241        }
1242        out.sort_unstable();
1243        out.dedup();
1244    }
1245
1246    /// Queries all items overlapping circle `(center, radius)`, writing deduplicated IDs into `out`.
1247    ///
1248    /// # Arguments
1249    ///
1250    /// - `Vec2` - Query circle center.
1251    /// - `f32` - Query radius.
1252    /// - `&mut Vec<u64>` - Reusable output buffer (cleared and deduplicated).
1253    pub fn query_radius_into(&self, center: Vec2, radius: f32, out: &mut Vec<u64>) {
1254        out.clear();
1255        if !radius.is_finite() || radius < 0.0 {
1256            return;
1257        }
1258        let inv: f32 = self.get_inv_cell_size();
1259        let min_cx: i32 = ((center.get_x() - radius) * inv).floor() as i32;
1260        let max_cx: i32 = ((center.get_x() + radius) * inv).floor() as i32;
1261        let min_cy: i32 = ((center.get_y() - radius) * inv).floor() as i32;
1262        let max_cy: i32 = ((center.get_y() + radius) * inv).floor() as i32;
1263        let buckets: &[SpatialHashBucket2D] = self.get_buckets();
1264        let entries: &[SpatialHashEntry2D] = self.get_entries();
1265        let mask: usize = buckets.len() - 1;
1266        for cy in min_cy..=max_cy {
1267            for cx in min_cx..=max_cx {
1268                let mut slot: usize = spatial_hash_2d(cx, cy) & mask;
1269                loop {
1270                    let bucket: SpatialHashBucket2D = buckets[slot];
1271                    if bucket.head == SPATIAL_EMPTY_SLOT {
1272                        break;
1273                    }
1274                    if bucket.cx == cx && bucket.cy == cy {
1275                        let mut cursor: usize = bucket.head;
1276                        while cursor != SPATIAL_EMPTY_SLOT {
1277                            let entry: SpatialHashEntry2D = entries[cursor];
1278                            if entry.bounds.intersects_circle(center, radius) {
1279                                out.push(entry.id);
1280                            }
1281                            cursor = entry.next;
1282                        }
1283                        break;
1284                    }
1285                    slot = (slot + 1) & mask;
1286                }
1287            }
1288        }
1289        out.sort_unstable();
1290        out.dedup();
1291    }
1292
1293    /// Queries items within `(center, radius)` into the grid's internal reusable scratch slice.
1294    ///
1295    /// # Arguments
1296    ///
1297    /// - `Vec2` - Query circle center.
1298    /// - `f32` - Query radius.
1299    ///
1300    /// # Returns
1301    ///
1302    /// - `&[u64]` - Deduplicated matching IDs stored in the internal scratch buffer.
1303    #[must_use]
1304    pub fn query_radius(&mut self, center: Vec2, radius: f32) -> &[u64] {
1305        let mut scratch: Vec<u64> = take(self.get_mut_query_scratch());
1306        self.query_radius_into(center, radius, &mut scratch);
1307        self.set_query_scratch(scratch);
1308        self.get_query_scratch()
1309    }
1310}
1311
1312/// Zero-allocation open-addressed uniform-cell 3D spatial hash grid operations.
1313impl SpatialHashGrid3D {
1314    /// Creates an empty `SpatialHashGrid3D` with uniform `cell_size`.
1315    ///
1316    /// # Arguments
1317    ///
1318    /// - `f32` - Cell edge length (clamped to `>= 1e-4`).
1319    ///
1320    /// # Returns
1321    ///
1322    /// - `Self` - Pre-allocated 3D spatial hash grid.
1323    #[must_use]
1324    pub fn new(cell_size: f32) -> Self {
1325        let safe_size: f32 = if cell_size.is_finite() && cell_size > 1e-4 {
1326            cell_size
1327        } else {
1328            1.0
1329        };
1330        Self {
1331            cell_size: safe_size,
1332            inv_cell_size: 1.0 / safe_size,
1333            occupied_buckets: 0,
1334            buckets: vec![
1335                SpatialHashBucket3D {
1336                    cx: 0,
1337                    cy: 0,
1338                    cz: 0,
1339                    head: SPATIAL_EMPTY_SLOT,
1340                };
1341                SPATIAL_HASH_INIT_CAP
1342            ],
1343            touched_buckets: Vec::with_capacity(SPATIAL_HASH_INIT_CAP / 2),
1344            entries: Vec::with_capacity(SPATIAL_HASH_INIT_CAP),
1345            query_scratch: Vec::with_capacity(64),
1346        }
1347    }
1348
1349    /// Clears all entries in O(active_cells) time while retaining every internal buffer's capacity.
1350    pub fn clear(&mut self) {
1351        let mut touched: Vec<usize> = take(self.get_mut_touched_buckets());
1352        let buckets: &mut Vec<SpatialHashBucket3D> = self.get_mut_buckets();
1353        for &slot in &touched {
1354            buckets[slot].head = SPATIAL_EMPTY_SLOT;
1355        }
1356        touched.clear();
1357        self.set_touched_buckets(touched);
1358        self.get_mut_entries().clear();
1359        self.set_occupied_buckets(0);
1360    }
1361
1362    /// Doubles the open-addressed 3D bucket table when load exceeds 65% and rehashes active cells.
1363    fn grow_buckets(&mut self) {
1364        let old_buckets: Vec<SpatialHashBucket3D> = take(self.get_mut_buckets());
1365        let old_touched: Vec<usize> = take(self.get_mut_touched_buckets());
1366        let new_cap: usize = (old_buckets.len() * 2).max(SPATIAL_HASH_INIT_CAP);
1367        let mask: usize = new_cap - 1;
1368        let mut new_buckets: Vec<SpatialHashBucket3D> = vec![
1369            SpatialHashBucket3D {
1370                cx: 0,
1371                cy: 0,
1372                cz: 0,
1373                head: SPATIAL_EMPTY_SLOT,
1374            };
1375            new_cap
1376        ];
1377        let mut new_touched: Vec<usize> = Vec::with_capacity(old_touched.len() * 2);
1378        for &old_slot in &old_touched {
1379            let bucket: SpatialHashBucket3D = old_buckets[old_slot];
1380            if bucket.head == SPATIAL_EMPTY_SLOT {
1381                continue;
1382            }
1383            let mut slot: usize = spatial_hash_3d(bucket.cx, bucket.cy, bucket.cz) & mask;
1384            while new_buckets[slot].head != SPATIAL_EMPTY_SLOT {
1385                slot = (slot + 1) & mask;
1386            }
1387            new_buckets[slot] = bucket;
1388            new_touched.push(slot);
1389        }
1390        self.set_buckets(new_buckets);
1391        self.set_touched_buckets(new_touched);
1392    }
1393
1394    /// Inserts an item `(id, bounds)` into every 3D cell overlapped by `bounds`.
1395    ///
1396    /// # Arguments
1397    ///
1398    /// - `u64` - Entity identifier.
1399    /// - `AxisAlignedBox3D` - World-space 3D bounding box.
1400    pub fn insert_aabb(&mut self, id: u64, bounds: AxisAlignedBox3D) {
1401        let norm: AxisAlignedBox3D = AxisAlignedBox3D::new(
1402            bounds.get_min().min(bounds.get_max()),
1403            bounds.get_min().max(bounds.get_max()),
1404        );
1405        let inv: f32 = self.get_inv_cell_size();
1406        let min_cx: i32 = (norm.get_min().get_x() * inv).floor() as i32;
1407        let max_cx: i32 = (norm.get_max().get_x() * inv).floor() as i32;
1408        let min_cy: i32 = (norm.get_min().get_y() * inv).floor() as i32;
1409        let max_cy: i32 = (norm.get_max().get_y() * inv).floor() as i32;
1410        let min_cz: i32 = (norm.get_min().get_z() * inv).floor() as i32;
1411        let max_cz: i32 = (norm.get_max().get_z() * inv).floor() as i32;
1412        for cz in min_cz..=max_cz {
1413            for cy in min_cy..=max_cy {
1414                for cx in min_cx..=max_cx {
1415                    if self.get_occupied_buckets() * 10 >= self.get_buckets().len() * 6 {
1416                        self.grow_buckets();
1417                    }
1418                    let mask: usize = self.get_buckets().len() - 1;
1419                    let mut slot: usize = spatial_hash_3d(cx, cy, cz) & mask;
1420                    let mut is_new_bucket: bool = false;
1421                    loop {
1422                        let bucket: SpatialHashBucket3D = self.get_buckets()[slot];
1423                        if bucket.head == SPATIAL_EMPTY_SLOT {
1424                            is_new_bucket = true;
1425                            break;
1426                        }
1427                        if bucket.cx == cx && bucket.cy == cy && bucket.cz == cz {
1428                            break;
1429                        }
1430                        slot = (slot + 1) & mask;
1431                    }
1432                    let prev_head: usize = self.get_buckets()[slot].head;
1433                    let entry_idx: usize = self.get_entries().len();
1434                    self.get_mut_entries().push(SpatialHashEntry3D {
1435                        id,
1436                        bounds: norm,
1437                        next: prev_head,
1438                    });
1439                    let bucket_mut: &mut SpatialHashBucket3D = &mut self.get_mut_buckets()[slot];
1440                    bucket_mut.cx = cx;
1441                    bucket_mut.cy = cy;
1442                    bucket_mut.cz = cz;
1443                    bucket_mut.head = entry_idx;
1444                    if is_new_bucket {
1445                        self.get_mut_touched_buckets().push(slot);
1446                        let next_occ: usize = self.get_occupied_buckets() + 1;
1447                        self.set_occupied_buckets(next_occ);
1448                    }
1449                }
1450            }
1451        }
1452    }
1453
1454    /// Inserts a 3D point `(id, position)` into its enclosing grid cell.
1455    ///
1456    /// # Arguments
1457    ///
1458    /// - `u64` - Entity identifier.
1459    /// - `Vec3` - World-space 3D position.
1460    pub fn insert_point(&mut self, id: u64, position: Vec3) {
1461        if !position.get_x().is_finite()
1462            || !position.get_y().is_finite()
1463            || !position.get_z().is_finite()
1464        {
1465            return;
1466        }
1467        self.insert_aabb(id, AxisAlignedBox3D::new(position, position));
1468    }
1469
1470    /// Queries all items overlapping `query_box`, writing deduplicated IDs into `out`.
1471    ///
1472    /// # Arguments
1473    ///
1474    /// - `AxisAlignedBox3D` - Query 3D bounding box.
1475    /// - `&mut Vec<u64>` - Reusable output buffer.
1476    pub fn query_aabb_into(&self, query_box: AxisAlignedBox3D, out: &mut Vec<u64>) {
1477        out.clear();
1478        let inv: f32 = self.get_inv_cell_size();
1479        let min_cx: i32 = (query_box.get_min().get_x() * inv).floor() as i32;
1480        let max_cx: i32 = (query_box.get_max().get_x() * inv).floor() as i32;
1481        let min_cy: i32 = (query_box.get_min().get_y() * inv).floor() as i32;
1482        let max_cy: i32 = (query_box.get_max().get_y() * inv).floor() as i32;
1483        let min_cz: i32 = (query_box.get_min().get_z() * inv).floor() as i32;
1484        let max_cz: i32 = (query_box.get_max().get_z() * inv).floor() as i32;
1485        let buckets: &[SpatialHashBucket3D] = self.get_buckets();
1486        let entries: &[SpatialHashEntry3D] = self.get_entries();
1487        let mask: usize = buckets.len() - 1;
1488        for cz in min_cz..=max_cz {
1489            for cy in min_cy..=max_cy {
1490                for cx in min_cx..=max_cx {
1491                    let mut slot: usize = spatial_hash_3d(cx, cy, cz) & mask;
1492                    loop {
1493                        let bucket: SpatialHashBucket3D = buckets[slot];
1494                        if bucket.head == SPATIAL_EMPTY_SLOT {
1495                            break;
1496                        }
1497                        if bucket.cx == cx && bucket.cy == cy && bucket.cz == cz {
1498                            let mut cursor: usize = bucket.head;
1499                            while cursor != SPATIAL_EMPTY_SLOT {
1500                                let entry: SpatialHashEntry3D = entries[cursor];
1501                                if aabb3d_intersects(entry.bounds, query_box) {
1502                                    out.push(entry.id);
1503                                }
1504                                cursor = entry.next;
1505                            }
1506                            break;
1507                        }
1508                        slot = (slot + 1) & mask;
1509                    }
1510                }
1511            }
1512        }
1513        out.sort_unstable();
1514        out.dedup();
1515    }
1516
1517    /// Queries all items intersecting sphere `(center, radius)`, writing deduplicated IDs into `out`.
1518    ///
1519    /// # Arguments
1520    ///
1521    /// - `Vec3` - Query sphere center.
1522    /// - `f32` - Query sphere radius.
1523    /// - `&mut Vec<u64>` - Reusable output buffer.
1524    pub fn query_sphere_into(&self, center: Vec3, radius: f32, out: &mut Vec<u64>) {
1525        out.clear();
1526        if !radius.is_finite() || radius < 0.0 {
1527            return;
1528        }
1529        let inv: f32 = self.get_inv_cell_size();
1530        let min_cx: i32 = ((center.get_x() - radius) * inv).floor() as i32;
1531        let max_cx: i32 = ((center.get_x() + radius) * inv).floor() as i32;
1532        let min_cy: i32 = ((center.get_y() - radius) * inv).floor() as i32;
1533        let max_cy: i32 = ((center.get_y() + radius) * inv).floor() as i32;
1534        let min_cz: i32 = ((center.get_z() - radius) * inv).floor() as i32;
1535        let max_cz: i32 = ((center.get_z() + radius) * inv).floor() as i32;
1536        let buckets: &[SpatialHashBucket3D] = self.get_buckets();
1537        let entries: &[SpatialHashEntry3D] = self.get_entries();
1538        let mask: usize = buckets.len() - 1;
1539        for cz in min_cz..=max_cz {
1540            for cy in min_cy..=max_cy {
1541                for cx in min_cx..=max_cx {
1542                    let mut slot: usize = spatial_hash_3d(cx, cy, cz) & mask;
1543                    loop {
1544                        let bucket: SpatialHashBucket3D = buckets[slot];
1545                        if bucket.head == SPATIAL_EMPTY_SLOT {
1546                            break;
1547                        }
1548                        if bucket.cx == cx && bucket.cy == cy && bucket.cz == cz {
1549                            let mut cursor: usize = bucket.head;
1550                            while cursor != SPATIAL_EMPTY_SLOT {
1551                                let entry: SpatialHashEntry3D = entries[cursor];
1552                                if aabb3d_intersects_sphere(entry.bounds, center, radius) {
1553                                    out.push(entry.id);
1554                                }
1555                                cursor = entry.next;
1556                            }
1557                            break;
1558                        }
1559                        slot = (slot + 1) & mask;
1560                    }
1561                }
1562            }
1563        }
1564        out.sort_unstable();
1565        out.dedup();
1566    }
1567
1568    /// Queries items intersecting `(center, radius)` into the grid's internal reusable scratch slice.
1569    ///
1570    /// # Arguments
1571    ///
1572    /// - `Vec3` - Query sphere center.
1573    /// - `f32` - Query sphere radius.
1574    ///
1575    /// # Returns
1576    ///
1577    /// - `&[u64]` - Deduplicated matching IDs stored in the internal scratch buffer.
1578    #[must_use]
1579    pub fn query_sphere(&mut self, center: Vec3, radius: f32) -> &[u64] {
1580        let mut scratch: Vec<u64> = take(self.get_mut_query_scratch());
1581        self.query_sphere_into(center, radius, &mut scratch);
1582        self.set_query_scratch(scratch);
1583        self.get_query_scratch()
1584    }
1585}