1use super::*;
2
3impl Bounds2D {
5 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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
152impl Default for QuadtreeConfig {
154 fn default() -> Self {
160 Self {
161 max_leaf_items: DEFAULT_TREE_LEAF_CAPACITY,
162 max_depth: DEFAULT_QUADTREE_MAX_DEPTH,
163 }
164 }
165}
166
167impl Quadtree2D {
169 #[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 #[must_use]
206 pub fn len(&self) -> usize {
207 self.get_positions().len()
208 }
209
210 #[must_use]
216 pub fn is_empty(&self) -> bool {
217 self.get_positions().is_empty()
218 }
219
220 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 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 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 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 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 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 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 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 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 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 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 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 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
611impl Default for OctreeConfig {
613 fn default() -> Self {
619 Self {
620 max_leaf_items: DEFAULT_TREE_LEAF_CAPACITY,
621 max_depth: DEFAULT_OCTREE_MAX_DEPTH,
622 }
623 }
624}
625
626impl Octree3D {
628 #[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 #[must_use]
664 pub fn len(&self) -> usize {
665 self.get_item_bounds().len()
666 }
667
668 #[must_use]
674 pub fn is_empty(&self) -> bool {
675 self.get_item_bounds().is_empty()
676 }
677
678 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 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 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 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 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 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 pub fn insert_point(&mut self, id: u64, position: Vec3) -> bool {
861 self.insert(id, AxisAlignedBox3D::new(position, position))
862 }
863
864 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 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 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 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 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 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 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 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
1059impl SpatialHashGrid2D {
1061 #[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 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 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 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 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 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 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 #[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
1312impl SpatialHashGrid3D {
1314 #[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 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 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 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 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 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 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 #[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}