-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSpatialHashGrid.java
More file actions
87 lines (77 loc) · 2.82 KB
/
Copy pathSpatialHashGrid.java
File metadata and controls
87 lines (77 loc) · 2.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/*
* Authors: Jerry Li & Victor Jiang
* Date: June 13, 2025
* Description: This class is used to optimize collision detection by dividing the world into cells so that lookup of nearby
* possible collision objects is more efficient
*/
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.LongConsumer;
/**
* Generic spatial hash grid for efficient proximity queries.
*/
public class SpatialHashGrid<T> {
private Map<Long, CopyOnWriteArrayList<T>> grid = new HashMap<>();
private float cellSize;
private HashSet<T> querySet = new HashSet<>();
private CopyOnWriteArrayList<T> queryList = new CopyOnWriteArrayList<>();
public SpatialHashGrid(float cellSize) {
this.cellSize = cellSize;
}
/** Clears all cells. */
public void clear() {
grid.clear();
}
private static long cellKey(int cx, int cy) {
return ((long) cx << 32) ^ (cy & 0xffffffffL);
}
private void foreachCell(float x, float y, float radius, LongConsumer fn) {
int minX = 0;
int maxX = 0;
int minY = 0;
int maxY = 0;
int cx = 0;
int cy = 0;
minX = (int) Math.floor((x - radius) / cellSize);
maxX = (int) Math.floor((x + radius) / cellSize);
minY = (int) Math.floor((y - radius) / cellSize);
maxY = (int) Math.floor((y + radius) / cellSize);
for (cx = minX; cx <= maxX; cx++) {
for (cy = minY; cy <= maxY; cy++) {
fn.accept(cellKey(cx, cy));
}
}
}
/** Inserts obj into all cells overlapped by its radius at (x,y). */
public void insert(T obj, float x, float y, float radius) {
foreachCell(x, y, radius, key -> {
grid.computeIfAbsent(key, k -> new CopyOnWriteArrayList<>()).add(obj);
});
}
/** Removes obj from cells overlapped by its radius at (x,y). */
public void remove(T obj, float x, float y, float radius) {
foreachCell(x, y, radius, key -> {
CopyOnWriteArrayList<T> list = grid.get(key);
if (list != null) {
list.remove(obj);
if (list.isEmpty()) grid.remove(key);
}
});
}
/** Updates obj from old to new position. */
public void update(T obj, float oldX, float oldY, float newX, float newY, float radius) {
remove(obj, oldX, oldY, radius);
insert(obj, newX, newY, radius);
}
/** Returns all objects within radius of the given position. */
public List<T> queryNearby(float x, float y, float radius) {
querySet.clear();
foreachCell(x, y, radius, key -> {
CopyOnWriteArrayList<T> list = grid.get(key);
if (list != null) querySet.addAll(list);
});
queryList.clear();
queryList.addAll(querySet);
return queryList;
}
}